Go Modules 通过 GOPRIVATE 环境变量识别私有仓库域名,如 GOPRIVATE=git.example.com,gitea.internal,支持通配符;设置后跳过 ?go-get=1 探测,直接调用 git clone,依赖 Git 凭据配置实现自动认证。

Go Modules 怎么识别私有仓库域名?
Go 默认只信任 github.com、gitlab.com 等公开域名,遇到 git.example.com 或 gitea.internal 这类私有地址会直接报错:unrecognized import path "git.example.com/my/project": https fetch: Get "https://git.example.com/my/project?go-get=1": dial tcp: lookup git.example.com: no such host(或 404/403)。根本原因是 Go 在解析 import 路径时,会先发一个 ?go-get=1 的 HTTP 请求去探测仓库元信息,而私有 Git 服务通常不提供该接口,或未配置正确响应。
解决方式不是改 Git 服务,而是告诉 Go:“这个域名下的路径,别走 HTTPS 探测,直接用 Git 协议拉取”。核心配置项是 GOPRIVATE 环境变量:
-
GOPRIVATE=git.example.com,gitea.internal—— 多个域名用英文逗号分隔,支持通配符:GOPRIVATE=*.example.com - 必须在运行
go build、go get前设置,推荐写入 shell 配置(如~/.zshrc)并重载 - 设置后,Go 就不会对这些域名发起
?go-get=1请求,而是直接调用git clone,此时依赖你本地的 Git 凭据配置
Git 凭据怎么让 go get 自动登录私有 GitLab/Gitea?
设置了 GOPRIVATE 后,常见错误变成:fatal: could not read Username for 'https://git.example.com': No such device or address。这是因为 Go 调用 git clone 时走的是 HTTPS 协议,而你的 Git 没配好凭据,无法自动填用户名密码或 Token。
推荐用 Git 的 credential.helper 配合 Personal Access Token(PAT):
- GitLab:在用户 Settings → Access Tokens 创建 token,勾选
read_repository(api权限非必需) - Gitea:在用户 Settings → Applications → Manage Application → Create Personal Access Token,勾选
read:repository - 执行
git config --global credential.helper store(明文存磁盘,开发机可用),然后手动触发一次 clone:git clone https://git.example.com/user/repo.git,输入用户名 + Token 当密码,Git 就会存下来 - 更安全的替代:用
git-credential-libsecret(Linux)、git-credential-manager(Windows/macOS),避免明文落盘
为什么 go mod download 总卡住或超时?
即使 GOPRIVATE 和凭据都对了,go mod download 仍可能卡在某个模块,尤其当私有仓库启用了自签名证书、或反向代理拦截了 Git 流量。
关键排查点:
- 确认 Git 能直连:手动跑
git ls-remote -h https://git.example.com/group/lib.git,看是否返回 refs。如果失败,Go 肯定也失败 - 自签名证书:Git 默认校验证书。若用内网 CA,需运行
git config --global http."https://git.example.com/".sslCAInfo /path/to/ca.crt;或临时关闭验证(不推荐):git config --global http."https://git.example.com/".sslVerify false - Gitea 特别注意:默认关闭
DISABLE_HTTP_GIT,但若反向代理(如 Nginx)没透传Content-Type或Transfer-Encoding,Git over HTTP 会静默失败。检查 Gitea 日志是否有git upload-pack相关 error - GitLab CE/EE:确认
gitlab_rails['git_max_size']和nginx['client_max_body_size']足够大(至少 50m),否则大模块下载中断
go get 能否指定分支或 tag?如何控制私有模块版本?
可以,语法和公开模块完全一致,但要注意 Go Modules 的版本识别逻辑依赖 Git 的 tag 格式。
操作要点:
- 打 tag 必须符合语义化版本格式:
v1.2.3(开头带v),否则go list -m -versions不会列出 - 指定 commit:用
go get git.example.com/user/repo@abcd123,但该 commit 必须在 default branch(通常是main或master)上,否则go mod tidy会报no matching versions - 指定分支:用
go get git.example.com/user/repo@dev,但 Go 不会把分支名当版本,go.mod里记录的是对应 commit hash,且后续go get -u不会自动升级到新 commit - 私有模块的
go.sum条目和公开模块无区别,但若更换私有仓库地址(如从gitlab.internal迁移到gitea.internal),需手动go mod edit -replace并go mod tidy刷新校验和
最易忽略的一点:私有模块的 go.mod 文件里写的 module path(如 module git.example.com/group/lib)必须和实际 import 路径、Git 仓库克隆 URL 的域名部分严格一致,大小写、子路径都不能错——Go 不做重定向或别名解析。










