无法使用os/exec包执行go文件

sub*_*ngh 4 go

我正在关注编写我的网络应用程序的golang教程.我正在修改教程页面中的代码,以便我可以执行保存的页面作为go代码(类似于go playground).但是当我尝试使用os/exec包执行保存的go文件时,它会抛出以下错误.

exec:"go run testcode.go":在$ PATH中找不到可执行文件

以下是我修改过的代码:

// Structure to hold the Page
type Page struct {
    Title  string
    Body   []byte
    Output []byte
}

// saving the page
func (p *Page) save() { // difference between func (p *Page) and func (p Page)
    filename := p.Title + ".go"
    ioutil.WriteFile(filename, p.Body, 0777)
}

// handle for the editing
func editHandler(w http.ResponseWriter, r *http.Request) {
    title := r.URL.Path[len("/edit/"):]

    p, err := loadPage(title)

    if err != nil {
        p = &Page{Title: title}
    }
    htmlTemp, _ := template.ParseFiles("edit.html")
    htmlTemp.Execute(w, p)
}

// saving the page
func saveHandler(w http.ResponseWriter, r *http.Request) {
    title := r.URL.Path[len("/save/"):]
    body := r.FormValue("body")

    p := Page{Title: title, Body: []byte(body)}
    p.save()

    http.Redirect(w, r, "/exec/"+title, http.StatusFound) // what is statusfound
}

// this function will execute the code.
func executeCode(w http.ResponseWriter, r *http.Request) {

    title := r.URL.Path[len("/exec/"):]

    cmd := "go run " + title + ".go"
    //cmd = "go"
    fmt.Print(cmd)
    out, err := exec.Command(cmd).Output()

    if err != nil {
        fmt.Print("could not execute")
        fmt.Fprint(w, err)
    } else {
        p := Page{Title: title, Output: out}

        htmlTemp, _ := template.ParseFiles("output.html")
        htmlTemp.Execute(w, p)
    }
}
Run Code Online (Sandbox Code Playgroud)

请告诉我为什么我无法执行go文件.

fab*_*ioM 16

您正在以错误的方式调用命令.第一个字符串是可执行文件的完整路径

os.exec.Command:func Command(name string, arg ...string)

所以你要 exec.Command("/usr/bin/go", "run", title+".go")