【Golang】通过私有库安装依赖

Posted by 西维蜀黍 on 2020-07-06, Last Modified on 2023-04-10

Situation

公司一个golang的项目,使用到了公司的私有仓库,去执行go mod tidy(下载依赖)的时候,到download公司私有库的时候就报错,报错信息也不明显,只是提示找不到影响版本unkown revision。

  • go mod tidy - 下载更新依赖
  • go install 这种下载依赖的方式其实是通过go get的方式去下载的
  • go insall -x - 加上-x命令,可以查看更多的错误信息

Solution

升级 git 版本

go mod调用链中会用到一些git指令,当git版本比较旧时,调用失败产生错误,并给出歧义的提示信息,提示unknown revision。

# 安装最新的 git
$ brew install git

$ which git
/usr/bin/git
$ git --version
git version 2.17.2 (Apple Git-113)

# 通过 brew link 将 git 指向我们通过 Homebrew 安装的 git
$ brew link git --overwrite

$ which git
/usr/bin/git
$ git --version
git version 2.27.0

声明私有库路径

$ go env -w GOPRIVATE="git.xxx.com"

# OR
$ vim ~/.zshrc    
# add content
GONOPROXY="git.xxx.com"
GONOSUMDB="git.xxx.com"

if not, you will get error

go: git.xxx.com/yyy/common/log@v0.2.0: reading git.xxx.com/yyy/common/log/go.mod at revision v0.2.0: git ls-remote -q origin in /Users/aaa/go/pkg/mod/cache/vcs/bcdc7826afeb8809b317309daadd20c0355335a5b3df06e7fb4fcba5c7cf2ccb: exit status 128:
        fatal: could not read Username for 'https://git.xxx.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.

修改git配置

go install/mod tidy 去下载依赖时,是通过git命令去下载的,而且默认是 HTTPS 协议去下载的,建议是修改为ssh协议去获取

通过修改文件方式,去到当前用户目录修改.gitconfig文件,新增如下,注意私有库是http还是https

[url "gitlab@git.xxx.com:"]
    insteadOf = https://git.xxx.com/

或者,通过命令行形式,直接执行命令如下:

$ git config --global url."gitlab@git.xxx.com:<port>".insteadOf "http://gitlab.xxx.com/"

if not, you will get error

$ go mod tidy
go: git.xxx.com/yyy/common/log@v0.2.0: reading git.xxx.com/yyy/common/log/go.mod at revision v0.2.0: git ls-remote -q origin in /Users/aaa/go/pkg/mod/cache/vcs/bcdc7826afeb8809b317309daadd20c0355335a5b3df06e7fb4fcba5c7cf2ccb: exit status 128:
        fatal: could not read Username for 'https://git.xxx.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.

然后执行go install 或者 go mod tidy确认是否可以正常下载依赖

Reference