简体   繁体   English

使用golang exec.Command运行go install

[英]running go install with golang exec.Command

I'm trying to write some code for a webhook, that will call go install. 我正在尝试为Webhook编写一些代码,这将称为go install。 The problem i'm having is that the GOPATH isn't set when i call any go commands with exec.Command 我遇到的问题是,当我使用exec.Command调用任何go命令时,未设置GOPATH

func exec_cmd(w http.ResponseWriter, cmd string, args ...string) {
    command := exec.Command(cmd, args...)
    var out bytes.Buffer
    var stderr bytes.Buffer
    command.Stdout = &out
    command.Stderr = &stderr
    err := command.Run()
    if err != nil {
        errstring := fmt.Sprintf(fmt.Sprint(err) + ": " + stderr.String())
        io.WriteString(w, errstring)
    }
    io.WriteString(w, out.String())
    fmt.Println(out.String())
}

func webhook(w http.ResponseWriter, r *http.Request) {
    exec_cmd(w, "go", "install", "github.com/me/myrepo/mything")
}

func test(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "test")
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/webhook", webhook)
    mux.HandleFunc("/", test)
    http.ListenAndServe(":8000", mux)
}

when the webhook endpoint is hit, it gives: 当webhook端点被命中时,它给出:

exit status 1: can't load package: package github.com/me/myrepo/mything: cannot find package "github.com/me/myrepo/mything" in any of:
    /usr/lib/go-1.6/src/github.com/me/myrepo/mything (from $GOROOT)
    ($GOPATH not set)

How would i go about making sure the GOPATH is set in this context? 我将如何确保在这种情况下设置了GOPATH?

If i run "go install github.com/me/myrepo/mything" from the command line, it works fine. 如果我从命令行运行“ go install github.com/me/myrepo/mything”,它将正常运行。

Are you running this in your editor context, or in a container perhaps? 您是在编辑器上下文中还是在容器中运行它? It won't work in a context without the GOPATH env variable set. 如果未设置GOPATH env变量,则无法在上下文中使用。

If running with go run main.go, does it work? 如果使用go run main.go进行运行,是否可以运行? It works for me in that context without modifying your code. 在这种情况下,它对我有用,而无需修改您的代码。 As long as the parent context has access to GOPATH it should. 只要父上下文可以访问GOPATH,它就应该可以。 You could alternatively set it manually with something like this: 您也可以使用以下类似的方法手动设置它:

command.Env = append(os.Environ(), "GOPATH=/tmp/go")

Or you could set GOPATH (for install) and PATH (for go,git cmds) in the context this process will run in (probably preferable), for example in a systemd unit file. 或者,您可以在此过程将在其中运行(可能更可取)的上下文中(例如,在systemd单元文件中)设置GOPATH(用于安装)和PATH(用于go,git cmds)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM