背景
在后台项目的日常开发中经常需要引用,公司内部或外部的一些独立模块,比如公共框架,SDK,公共组件等。引用github的开源项目我们都知道只需配置一下 GOPROXY = goproxy.cn,direct 国内代理即可。那么对于引用公司内部的项目该如何配置呢,下面就把我在配置的过程中遇到的问题及解决方案贴在下面,希望对您有帮助。
问题一及解决方案:
问题: 在go build 或 go get的时候报:
invalid version: git fetch -f origin refs/heads/*:refs/heads/* refs/tags/*:refs/tags/* in xxxxxxxxxxxxxxxxxxxxxxxxxx : exit status 128:
fatal: Cannot prompt because user interactivity has been disabled.
fatal: Cannot prompt because user interactivity has been disabled.
remote: HTTP Basic: Access denied
fatal: Authentication failed for 'https://git.xxx.cn/xxxx/xxxxx.git/'
解决方案: 这个问题是goget拉取远程代码时默认是用了https的方式,这里我们只需要设置一下git的全局配置,改成用ssh的方式去拉取代码即可(前提是你在公司的代码管理平台上有自己的账号,并且在账号下关联了你本地的ssh key,注意:假设你公司的git仓库只支持http,那替换的时候也填http)。配置如下:
git config --global url.ssh://git@git.xxx.cn/.insteadOf https://git.xxx.cn/
配置完后 cat ~/.gitconfig 看一下git的全局配置文件中是否设置成功即可
注意:https://git.xxx.cn/xxxx/xxxxx.git/为你需要引用的模块名,git设置中git.xxx.cn为你公司的代码管理平台域名
问题二及解决方案
问题:
go mod download: git.xxx.cn/xxxx/xxxxx@v0.0.0-20220324061352-44585579a375: verifying go.mod: git.xxx.cn/xxxx/xxxxx@v0.0.0-20220324061352-44585579a375/go.mod: reading https://goproxy.cn/sumdb/sum.golang.org/lookup/git.xxx.cn/xxxx/xxxxx@v0.0.0-20220324061352-44585579a375: 404 Not Found
server response: not found: git.xxx.cn/xxxx/xxxxx@v0.0.0-20220324061352-44585579a375: unrecognized import path "git.xxx.cn/xxxx/xxxxx": https fetch: Get "https://git.xxx.cn/xxxx/xxxxx?go-get=1": dial tcp 172.16.1.216:443: connect: connection refused
解决方案:
看到404 Not Found我们大致就应该猜到是url不对。看上面的报错可以发现是私有仓库走了公共代理所导致的。执行:go env -w GOPRIVATE=git.xxx.cn/* 命名设置GOPRIVATE变量,让私有仓库不走公共代理即可。如果有多个域名之间用,分隔。执行上面的命令后,可以发现GONOPROXY 和 GONOSUMDB也同时被设置了。是因为GOPRIVATE的值将作为 GONOPROXY 和 GONOSUMDB 的默认值。
问题三及解决方案
问题: 在将ssh-key,关联到公司的gitlab仓库后,并且git也配置成按照ssh的方式拉取代码后,执行go mod tidy -v时,可能还会遇到如下报错:Permission denied (publickey)。
xxxxxxxx/gsdkclient: reading xxxxxxxx/gsdkclient/go.mod at revision v1.0.5: git ls-remote -q origin in C:\Users\admin\go\pkg\mod\cache\vcs\30152cfe5d862d1fdc5dd4384d07e1406cef9bae07bc27d6dc62a744e6d72dc9: exit status 128:
admin@xxxxxxxx: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct acces
解决方案:出现这个问题是因为SSH 配置文件(~/.ssh/config)中没有正确的设置,进行如下配置大概率可以解决
Host git.xxxxxxx.com
User git
IdentityFile ~/.ssh/id_rsa
问题四及解决方案
问题: 解决了上面两个问题后,执行go build,会发现报很多如下之类的错
go: git.xxx.cn/xxxx/xxxxx@v0.0.0-20220324061352-44585579a375: missing go.sum entry for module providing package......; to add it:
go mod download git.xxx.cn/xxxx/xxxxx
解决方案:出现这个问题是因为我们在代码中直接使用了第三方库 ,但是go.mod中并没有跟着更新,就直接go build或go run了,可以使用go mod tidy 来整理依赖。 这个命令会:1.更新go.sum 2.下载新的依赖包 3.删除不需要的依赖包
问题五
假设你公司的git仓库只支持http访问,那除了问题一的在替换的时候使用http。go GOINSECURE环境变量也最好设置一下,如:go env -w GOINSECURE=git.xxxxxx.com