Go拉取私有仓库失败主因是认证缺失或GOPROXY干扰:需配置git凭据助手(HTTPS)或SSH密钥(SSH),并设置GOPRIVATE跳过代理直连,三者缺一不可。
执行 go get 或构建时出现类似错误,基本可判定为认证失败或 GOPROXY 配置干扰:
go: module example.com/internal/pkg@v0.1.0: reading example.com/internal/pkg/go.mod at revision v0.1.0: 404 Not Found
或更隐蔽的:
go: example.com/internal/pkg@v0.1.0: invalid version: git ls-remote -q origin in /tmp/gopath/pkg/mod/cache/vcs/...: exit status 128: Host key verification failed. fatal: Could not read from remote repository.
关键点:Go 默认用 git 命令克隆私有仓库,而它不读取 ~/.netrc 或 IDE 内置凭据,也不自动转发 SSH agent —— 必须显式配置凭证或改用 HTTPS+token/SSH+key。
适用于 GitLab、GitHub(启用 token)、自建 Gitea 等支持 HTTPS Basic Auth 的场景。Go 调用 git 时会触发系统级凭据管理器,但 Linux/macOS 默认不启用,需手动配。
git-credential-libsecret(GNOME)或 git-credential-osxkeychain(macOS),或直接用 store 后端(凭据明文存本地,仅限开发机)git config --global credential.helper store
go get 自动复用git ls-remote https://example.com/internal/pkg.git—— 不报 401 即成功
Go 模块路径如 git@example.com:org/repo.git 会被识别为 SSH 协议,此时 Go 会调用 git 执行 git clone git@example.com:org/repo.git。成败完全取决于本地 git 是否能连上。
git@ 开头,且与 ~/.ssh/config 中 Host 别名匹配(例如 Host example.com → User git)ssh -T git@example.com和
git ls-remote git@example.com:org/repo.git均需成功,否则
go get 必败go.mod 里写的是 https://example.com/org/repo,即使 ~/.ssh/config 配了也无效SSH_PRIVATE_KEY 并用 ssh-add 加载(注意权限:私钥文件 chmod 600)国内用户习惯设 GOPROXY=https://goproxy.cn,direct,但该代理**只缓存公开模块**,遇到私有域名(如 example.com)会 fallback 到 direct —— 看似没问题,实则 fallback 时仍走默认 git 行为,未受 proxy 控制,也就没继承你的认证配置。
export GOPROXY="https://goproxy.cn,direct" export GOPRIVATE="example.com,git.internal.company"
GOPRIVATE 值是逗号分隔的域名通配符(支持 * 和 **),匹配后 Go 会跳过 proxy 直连,并启用上述 git 凭据逻辑go env GOPRIVATE必须输出包含你的域名;再执行
go list -m example.com/internal/pkg,观察是否还报 404 或权限错私有模块不是“加个 token 就行”,而是 git 认证 + Go 协议路由 + 环境变量三者对齐。少一个环节,go mod tidy 就卡在 fetch 阶段不动。