dongmin4990 2017-03-21 11:16
浏览 117
已采纳

使用golang exec.Command运行go install

I'm trying to write some code for a webhook, that will call go install. The problem i'm having is that the GOPATH isn't set when i call any go commands with exec.Command

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:

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?

If i run "go install github.com/me/myrepo/mything" from the command line, it works fine.

  • 写回答

1条回答 默认 最新

  • douzai3399 2017-03-21 21:38
    关注

    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.

    If running with go run main.go, does it work? It works for me in that context without modifying your code. As long as the parent context has access to GOPATH it should. 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?