如何修复Go Mod Unknown Revision

在介绍 Go mod 之后,我们可能已经使用过 Go 模块和私有存储库。 在处理使用新的 Go 模块包管理和版本控制系统的 Go 项目并专门使用公共包时,我们通常不会遇到任何重大问题。

但是,当尝试将 Go 包导入私有存储库时,我们可能会在运行 Go build 或 Go modules 命令时遇到问题。 我们可能会看到如下问题:

$ go build
go: github.com/acme-corporation/internal-rpc-client@v0.1.5: unknown revision v0.1.5

如果你遇到过类似的错误,那么你并不孤单。 这意味着 Go 模块无法正确访问私有包。


访问私有仓库时如何解决Go mod unknown revision

1. 确保你已经设置了 GO111MODULE

确保你正确使用 Go 模块,这会告诉 Go 使用 Go 模块,以防你运行的是旧版本或 Go,或者错误地禁用了 Go 模块。 这是运行后续步骤所必需的。关于这个问题可以参考我们的 go语言:环境变量GOPROXY和GO111MODULE设置 文章

$ go env -w GO111MODULE=on

2. 将你的组织私有仓库添加到 GOPRIVATE

Go 团队正确地考虑了在使用 Go mod 时使用私有包的可能性,并创建了一个帮助工具来描述这种情况

go help module-private

The go command defaults to downloading modules from the public 
Go module mirror at proxy.golang.org. It also defaults 
to validating downloaded modules,regardless of source, 
against the public Go checksum database at sum.golang.org.

These defaults work well for publicly available source code.

The GOPRIVATE environment variable controls which modules
the go command considers to be private (not available publicly) 
and should therefore not use the proxy or checksum database. 
The variable is a comma-separated list of glob patterns 
(in the syntax of Go's path.Match) of module path prefixes.

For example,

GOPRIVATE=*.corp.example.com,rsc.io/private

因此,下一步应该如下所示,使用 GOPRIVATE 环境变量将我们的私有存储库设置为“private

$ go env -w GOPRIVATE=github.com/acme-corporation/internal-rpc-client

3. 确保您的 git 配置适用于私有存储库

Go mod 在后台使用 git 来检索远程包信息。 因此,你应该通过更新 git 配置来告诉 git 如何访问私有包

$ git config --global url."ssh://git@github.com:acme-corporation".insteadOf "https://github.com/acme-corporation"

这将允许我们的 git 客户端和 Go mod 使用我们的 ssh 密钥访问 github 并进行身份验证并访问私有存储库

4. 如果使用 2FA,请确保创建个人访问令牌

在 github 中,特别是如果你为你的组织使用 2FA,在这种情况下使用你的 ssh 密钥将不起作用,你将不得不创建一个个人访问令牌并使用它来访问你的私有存储库

$ git config --global url."https://:x-oauth-basic@github.com:acme-corporation".insteadOf "https://github.com/acme-corporation"