目录

golang 引用私有仓库

`

直接使用go get

直接使用go get …添加私有仓库依赖时,会出现以下错误:

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的方式来下载依赖,从而导致鉴权失败。

如果配置了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错误。

1.12版本解决方案

在1.11和1.12版本中,比较主流的解决方案是配置git强制采用ssh。

这个解决方案在许多博客、问答中都可以看到:

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。