解决golang cannot find package问题

这个问题一般是因为国内被墙的原因,解决办法如下:

  1. 错误信息,大概意思就是获取某个依赖包失败了
    main.go:7:2: cannot find package "github.com/ego008/goyoubbs/cronjob" in any of:
    /usr/local/go/src/github.com/ego008/goyoubbs/cronjob (from $GOROOT)
    /root/go/src/github.com/ego008/goyoubbs/cronjob (from $GOPATH)
    main.go:8:2: cannot find package "github.com/ego008/goyoubbs/getold" in any of:
    /usr/local/go/src/github.com/ego008/goyoubbs/getold (from $GOROOT)
    /root/go/src/github.com/ego008/goyoubbs/getold (from $GOPATH)
    main.go:9:2: cannot find package "github.com/ego008/goyoubbs/router" in any of:
    /usr/local/go/src/github.com/ego008/goyoubbs/router (from $GOROOT)
    /root/go/src/github.com/ego008/goyoubbs/router (from $GOPATH)
    main.go:10:2: cannot find package "github.com/ego008/goyoubbs/system" in any of:
    /usr/local/go/src/github.com/ego008/goyoubbs/system (from $GOROOT)
    /root/go/src/github.com/ego008/goyoubbs/system (from $GOPATH)
    main.go:11:2: cannot find package "github.com/xi2/httpgzip" in any of:
    /usr/local/go/src/github.com/xi2/httpgzip (from $GOROOT)
    /root/go/src/github.com/xi2/httpgzip (from $GOPATH)
    main.go:12:2: cannot find package "goji.io" in any of:
    /usr/local/go/src/goji.io (from $GOROOT)
    /root/go/src/goji.io (from $GOPATH)
    main.go:13:2: cannot find package "goji.io/pat" in any of:
    /usr/local/go/src/goji.io/pat (from $GOROOT)
    /root/go/src/goji.io/pat (from $GOPATH)
    main.go:14:2: cannot find package "golang.org/x/crypto/acme/autocert" in any of:
    /usr/local/go/src/golang.org/x/crypto/acme/autocert (from $GOROOT)
    /root/go/src/golang.org/x/crypto/acme/autocert (from $GOPATH)
    main.go:15:2: cannot find package "golang.org/x/net/http2" in any of:
    /usr/local/go/src/golang.org/x/net/http2 (from $GOROOT)
    /root/go/src/golang.org/x/net/http2 (from $GOPATH)
  2. 尝试用go get去解决问题。基本上会报timeout错误,还是不能解决问题
    go get golang.org/x/net/  .........
  3. 其实可以直接去github克隆一份必备的依赖包。解决方案(前提是你的开发环境gopath都正取配置了,这里就不说了)如下:
    进入 gopath src目录
    cd go/src
    makdir golang.org(这个gopath src下的文件做开发的都知道是干什么的)
    cd golang.org
    接下来你缺什么就创建什么,比如 cannot find package "golang.org/x/net/http2"
    mkdir x
    cd x
    git clone git@github.com:golang/net.git
    差XXXXXX就 git clone git@github.com:golang/XXXXXX.git
    如果觉得麻烦就按照下边操作吧,所有的全部clone下来
    cd go/src
    git clone https://github.com/MXi4oyu/golang.org.git
  4. 准备好后,进入你的项目目录下。然后go build等待一会后,一般没有输出就是成功了,会在当前目录下生成一个可执行文件
  5. 运行可执行文件./XXX. ok 项目正常跑起来了

2019-11-13 更新

golang 1.13版本支持go module了同时推出了方便中国开发者的代理

go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct

完美解决!