本文同步发布于我的博客。html
Golang
的发展能够用突飞猛进来形容,可是这并不是褒义词,而是说它在性能、功能上存在诸多不完善之处,相同的功能伴随着小版本的发展,也会出现破坏性的变化。git
可是既然选择了Golang
,不管合不合理,咱们都不得不忍受Russ Cox
对该语言天马行空、大刀阔斧的变动。github
本文简单介绍一下Go
语言在1.11
版本以后推出的go mod
使用私有仓库时遇到的问题。golang
go get
直接使用go get ...
添加私有仓库依赖时,会出现如下错误:ssh
get "gitlab.com/xxx": found meta tag get.metaImport{Prefix:"gitlab.com/xxx", VCS:"git", RepoRoot:"https://gitlab.com/xxx.git"} at //gitlab.com/xxx?go-get=1 go get gitlab.com/xxx: git ls-remote -q https://gitlab.com/xxx.git in /Users/sulin/go/pkg/mod/cache/vcs/91fae55e78195f3139c4f56af15f9b47ba7aa6ca0fa761efbd5b6e2b16d5159d: exit status 128: fatal: could not read Username for 'https://gitlab.com': terminal prompts disabled Confirm the import path was entered correctly. If this is a private repository, see https://golang.org/doc/faq#git_https for additional information.
从错误信息能够明显地看出来,咱们使用私有仓库时一般会配置ssh-pubkey
进行鉴权,可是go get
使用https
而非ssh
的方式来下载依赖,从而致使鉴权失败。gitlab
GOPROXY
错误若是配置了GOPROXY
代理,错误信息则是以下样式:性能
go get gitlab.com/xxx: module gitlab.com/xxx: reading https://goproxy.io/gitlab.com/xxx/@v/list: 404 Not Found
从错误信息能够看出,go get
经过代理服务拉取私有仓库,而代理服务固然不可能访问到私有仓库,从而出现了404错误。this
1.12
版本解决方案在1.11
和1.12
版本中,比较主流的解决方案是配置git
强制采用ssh
。url
这个解决方案在许多博客、问答中均可以看到:代理
git config --global url."git@gitlab.com:xxx/zz.git".insteadof "https://gitlab.com/xxx/zz.git"
可是它与GOPROXY
存在冲突,也就是说,在使用代理时,这个解决方案也是不生效的。
1.13
版本解决方案在1.13
版本以后,前面介绍的解决方案又会致使go get
出现另外一种错误:
get "gitlab.com/xxx/zz": found meta tag get.metaImport{Prefix:"gitlab.com/xxx/zz", VCS:"git", RepoRoot:"https://gitlab.com/xxx/zz.git"} at //gitlab.com/xxx/zz?go-get=1 verifying gitlab.com/xxx/zz@v0.0.1: gitlab.com/xxx/zz@v0.0.1: reading https://sum.golang.org/lookup/gitlab.com/xxx/zz@v0.0.1: 410 Gone
这个错误是由于新版本go mod
会对依赖包进行checksum
校验,可是私有仓库对sum.golang.org
是不可见的,它固然没有办法成功执行checksum
。
也就是说强制git
采用ssh
的解决办法在1.13
版本以后GG了。
固然Golang
在堵上窗户以前,也开了大门,它提供了一个更方便的解决方案:GOPRIVATE
环境变量。解决以上的错误,能够这样配置:
export GOPRIVATE=gitlab.com/xxx
它能够声明指定域名为私有仓库,go get
在处理该域名下的全部依赖时,会直接跳过GOPROXY
和CHECKSUM
等逻辑,从而规避掉前文遇到的全部问题。
另外域名gitlab.com/xxx
很是灵活,它默认是前缀匹配的,全部的gitlab.com/xxx
前缀的依赖模块都会被视为private-modules
,它对于企业、私有Group等有着一劳永逸的益处。
提示:若是你经过ssh
公钥访问私有仓库,记得配置git
拉取私有仓库时使用ssh
而非https
。
能够经过命令git config ...
的方式来配置。也能够像我这样,直接修改~/.gitconfig
添加以下配置:
[url "git@github.com:"] insteadOf = https://github.com/ [url "git@gitlab.com:"] insteadOf = https://gitlab.com/
便可强制go get
针对github.com
与gitlab.com
使用ssh
而非https
。
将来可能会有其余的变化,若是出现了的话,我会继续完善这篇文章。
顺便为本身写的日志库slf4go打个广告。