goprivate仅禁用代理和校验,认证依赖git凭据系统;go mod download报401或unknown revision实为git clone失败,需配置git credential或ssh密钥,且goprivate须精确匹配域名端口。

不能只靠 GOPRIVATE 就让私有模块下载成功——它只是告诉 Go “别走代理、别校验 checksum”,真正的认证还得靠 Git 自己。
为什么 go mod download 报 401 或 unknown revision
根本不是 Go 的问题,而是 go 命令底层调用 git clone 时失败了。Go 本身不处理用户名密码或 token,全交给 Git 凭据系统。常见现象包括:
-
go mod download卡住几秒后报unknown revision(其实是git clone连不上) - 明确报错
401 Unauthorized或Permission denied (publickey) -
git clone https://git.example.com/group/lib手动能通,但go mod download不行(说明凭据没被复用)
HTTPS 方式:用 git credential 存 token,别硬编码 URL
把 token 塞进 URL(如 https://token:x-oauth-basic@git.example.com/group/lib)看似简单,但会导致:
-
go.sum和go.mod里泄露凭证 -
go mod vendor后仍需运行时认证,且无法自动刷新 - 部分 Git 托管平台(如自建 Gitea)不支持该格式
正确做法是交由 Git 管理凭据:
- 运行
git config --global credential.helper store - 首次执行
git clone https://git.example.com/group/lib,输入用户名 + token(不是密码) - 后续所有
go mod操作自动复用该凭据 - 凭证明文存在
~/.git-credentials,生产环境建议改用cache或libsecret
SSH 方式:确保 ssh-agent 加载了私钥
Go 调用 git 时会走 SSH 协议,但不会读 ~/.ssh/config 里的别名(除非你显式配置 insteadOf)。关键点:
-
go.mod中的模块路径必须匹配 SSH 地址结构,例如module git.example.com/group/lib对应git@git.example.com:group/lib.git - 运行
ssh-add -l确认私钥已加载;没输出就先ssh-add ~/.ssh/id_rsa - 如果用非默认密钥名(如
id_rsa_company),需在~/.ssh/config中指定:Host git.example.com<br> IdentityFile ~/.ssh/id_rsa_company
-
GOINSECURE对 SSH 无效——它只跳过 HTTPS 的 TLS 校验,别乱设
GOPRIVATE 必须精确匹配域名+端口
设成 export GOPRIVATE=git.example.com 并不能覆盖 git.example.com:2222 或 dev.git.example.com。实际生效规则:
- 逗号分隔,无空格:
GOPRIVATE=git.example.com,my.company.internal -
*只支持前缀匹配:*.example.com匹配git.example.com,但不匹配example.com - 含端口必须写全:
git.example.com:2222,不能省略:2222 - 设完立刻验证:
go env GOPRIVATE,再跑go list -m all看是否还报verifying错误
最易忽略的是:即使 GOPRIVATE 设对了,只要 git clone 这一层不通,go mod download 就永远卡在认证环节——它根本不会尝试下一步。











