如何覆盖 go 模块中的依赖项?

How to override a dependency in go modules?

dep 中,您可以选择覆盖依赖项并让它指向不同的存储库,例如在下面的 https://github.com/kubermatic/glog-logrus 库中,需要将以下行添加到 Gopkg.toml 文件:

[[override]]
  name = "github.com/golang/glog"
  source = "github.com/kubermatic/glog-logrus"

然后在代码库中 import "github.com/golang/glog。但是,在 go modules 中我没有看到这样的选项?这让我认为唯一的解决方案是将导入更改为 github.com/kubermatic/glog-logrus.

谢谢!

这就是 replace 指令的用途。

引用自 wiki Go 1.11 Modules: When should I use the replace directive?

The replace directive allows you to supply another import path that might be another module located in VCS (GitHub or elsewhere), or on your local filesystem with a relative or absolute file path. The new import path from the replace directive is used without needing to update the import paths in the actual source code.

因此将其添加到主模块的 go.mod 文件中:

replace (
    github.com/golang/glog => github.com/kubermatic/glog-logrus v0.0.0
)

您还可以指示 go 工具为您进行此编辑:

go mod edit -replace github.com/golang/glog=github.com/kubermatic/glog-logrus@v0.0.0

(使用您感兴趣的版本。)

在此之后当您导入 github.com/golang/glog 时,将使用 github.com/kubermatic/glog-logrus(无需更改导入语句)。