14-Go Modules

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

1
2
3
4
5
go get: module github.com/unknown/com: git ls-remote -q origin in D:\IDEA\go\pkg\mod\cache\vcs\ca60e3dfa1619897170f0f21e6f875c057be28088185a4024963a17a2db23167: exit status 128:
Logon failed, use ctrl+c to cancel basic credential prompt.
fatal: could not read Username for 'https://github.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 的方式来下载依赖,从而导致鉴权失败。

Go官方已经回答了为什么 go get 使用 https 而非 ssh 方式的原因,简单来说就是为了安全考虑,防止中间人攻击

https://go.dev/doc/faq#git_https

Go 官方也为拉私有包的用户提供了一个方法,便是 .netrc 文件,这是 git 工具在命令行使用 https 方式访问时的认证文件。

如果配置了GOPROXY代理,错误信息则是如下样式:

1
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.111.12版本中,比较主流的解决方案是配置git强制采用ssh

    git config –global url.”git@gitlab.com:xxx/zz.git”.insteadof “https://gitlab.com/xxx/zz.git”

    但是它与GOPROXY存在冲突,也就是说,在使用代理时,这个解决方案也是不生效的。

  • 1.13版本之后,前面介绍的解决方案又会导致go get出现另一种错误:

    1
    2
    getgitlab.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了。

所以我们需要两步来解决这个问题,后面两步看情况。

  1. 设置GOPRIVATE环境变量。

    1
    export GOPRIVATE=gitlab.com/xxx

    它可以声明指定域名为私有仓库,go get 在处理该域名下的所有依赖时,会直接跳过 GOPROXYCHECKSUM 等逻辑,从而规避掉前文遇到的所有问题。

    另外域名gitlab.com/xxx非常灵活,它默认是前缀匹配的,所有的 gitlab.com/xxx 前缀的依赖模块都会被视为private-modules,它对于企业、私有Group等有着一劳永逸的益处。

  2. 如果你通过ssh公钥访问私有仓库,配置git拉取私有仓库时使用ssh而非https

    可以通过命令 git config ... 的方式来配置。也可以直接修改 ~/.gitconfig 添加如下配置:

    1
    2
    3
    4
    [url “git@github.com:”]  
    insteadOf = https://github.com/
    [url “git@gitlab.com:”]
    insteadOf = https://gitlab.com/

    即可强制 go get 针对 github.comgitlab.com 使用 ssh 而非 https

  3. 如果你通过 https 访问私有仓库,可以在用户根目录下的 .netrc 文件加上 git 仓库登录账号就行了。

    1
    echo "machine 仓库地址 login 用户名 password 密码" > ~/.netrc
  4. 如果私有库不支持 https 协议,设置跳过CA证书校验:go env -w GOINSECURE='gitlab.com/xxx'


14-Go Modules
https://flepeng.github.io/021-Go-11-安装和配置-Go-私有仓库下载/
作者
Lepeng
发布于
2024年11月11日
许可协议