如何使用带有环境变量或相对路径的替换指令

How to use replace directive with env var or relative path

我正在查看 go.mod:

的替换指令

https://thewebivore.com/using-replace-in-go-mod-to-point-to-your-local-module/

module github.com/pselle/foo

replace github.com/pselle/bar => /Users/pselle/Projects/bar

require (
    github.com/pselle/bar v1.0.0
)

在团队中工作时,这是非常愚蠢的,因为 url 是绝对的,除了你自己的机器之外,任何机器都会中断。

有没有办法使用环境变量或相对路径来指定替换指令?像这样:

replace github.com/pselle/bar => $GOPATH/src/github.com/pselle/bar

replace github.com/pselle/bar => ./github.com/pselle/bar

当 PWD 发生变化时,使用相对路径非常糟糕,使用带有环境变量的绝对路径会好得多。

这应该可以回答您的问题:

环境变量不起作用,但您可以使用相对于固定位置(模块的根)的相对路径。从回答可以看出:

The path you specify for the replace directive must be either an absolute path or a relative path, relative to the module's root.

现在不可能。 There was a proposalusing 指令引入 go.mod 文件,这将允许重用环境变量进行替换。但是那个提议被拒绝了。据我所知,目前没有针对该问题引入简单解决方案的计划。

如果您与团队合作,您如何在许多开发人员机器上协调这些新代码?

为什么不直接将这个新代码签入 git。生产构建仍将通过 go.mod 和您的 semver 标签进行版本控制。您可以标记此开发推送。或者您可以随时拉取 @master 以获取最新信息。所有开发人员都可以在不中断生产的情况下处理这个通用代码。当准备好发布时,标记下一个工作提交并更新 go.mod 的 semver 标签。