如何让内部Go模块跨项目使用?私有模块拉取失败求助
解决Go私有GitLab模块导入失败问题
我之前在项目里用内部Go模块:
package main import ( "gitlab.example.com/team/project/internal/exitcodes" )
原本能正常工作,现在把这个模块移到新仓库gitlab.example.com/team/gocommon,导入路径改成gitlab.example.com/team/gocommon/exitcodes,生成了GitLab访问令牌并配置到~/.netrc:
machine gitlab.example.com login gogettoken password DBJMsPsGrFAiMq2MDRRT
但构建项目时失败,报错如下:
gitlab.example.com/team/gocommon/exitcodes: gitlab.example.com/team/gocommon@v0.0.0-20240503064125-dd1bc8fb4cf8: verifying module: gitlab.example.com/team/gocommon@v0.0.0-20240503064125-dd1bc8fb4cf8: reading https://sum.golang.org/lookup/gitlab.example.com/team/gocommon@v0.0.0-20240503064125-dd1bc8fb4cf8: 404 Not Found server response: not found: gitlab.example.com/team/gocommon@v0.0.0-20240503064125-dd1bc8fb4cf8: invalid version: git ls-remote -q origin in /tmp/gopath/pkg/mod/cache/vcs/5c5d3cb0b00b8d48278234b7d0c82797966117d16c9fedbd2cf87e471d549e5b: exit status 128: fatal: could not read Username for 'https://gitlab.example.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.
解决方案
1. 禁止Go校验私有模块的sum值
私有模块不会上传到公共的sum.golang.org,需要告诉Go跳过该域名下模块的校验:
go env -w GOPRIVATE=gitlab.example.com
也可以在项目根目录的go.env文件中添加:
GOPRIVATE=gitlab.example.com
2. 确保Git正确读取.netrc认证信息
- 检查
~/.netrc权限,必须设为600,否则Git会忽略该文件:chmod 600 ~/.netrc - 确认Git配置未覆盖.netrc设置,执行以下命令让Git优先使用.netrc凭证:
git config --global credential.helper ""
3. 给模块仓库打合法版本Tag
Go依赖语义化版本号(如v1.0.0),无Tag时生成的伪版本号可能出现识别问题。在gocommon仓库执行:
git tag v0.1.0 git push origin v0.1.0
随后在新项目中执行:
go get gitlab.example.com/team/gocommon@v0.1.0
4. 临时用replace指令测试(可选)
若以上步骤未解决,可在新项目的go.mod中添加replace指令,直接指向本地或仓库路径:
# 指向本地目录 replace gitlab.example.com/team/gocommon => ./path/to/local/gocommon # 或指向Git仓库SSH地址 replace gitlab.example.com/team/gocommon => git@gitlab.example.com:team/gocommon.git
测试通过后移除replace,改用正常版本导入。
内容的提问来源于stack exchange,提问作者Skeeve
相关产品推荐
相关产品推荐

