使用 'go build' 获取依赖项,即使它们在 vendor/

Using 'go build' fetches dependencies even though they are in vendor/

我正在尝试获取一个 Go 项目并将依赖项复制到 vendor/ 目录下,以便在我的项目中拥有该项目及其依赖项的完整源代码。然而,即使在这样做之后,删除 $GOPATH/pkg/mod 下的包并重新构建也会导致 Go 编译器重新获取所有依赖项,这需要相当长的时间。

这是我做的:

# Fetch the project, e.g. influx/telegraf
go get -d github.com/influxdata/telegraf

# CD into the project
cd $GOPATH/src/influxdata/telegraf

# Fetch the modules under vendor/ directory
go mod vendor

调用最后一个命令后,Go 将获取 pkg/mod 下的所有依赖项。不知道为什么会这样,但我猜是因为它需要正常构建项目,然后将获取的依赖项移动到 vendor/ 文件夹下。之后,我就可以成功构建了。但是,为了确保我不再需要这些依赖项,我完全删除了 pkg/mod 目录并重建了项目。 Go 编译器,出于某种原因,再次获取包。

我做错了什么吗?

谢谢!

vendor 文件夹并非在所有情况下都自动使用。

要确保从主模块的 vendor 文件夹加载依赖项,请将 -mod=vendor 传递给 go 工具。

如果go.mod文件指定的go版本为1.14或更高版本,则仅自动使用vendor文件夹(如果存在-mod=mod) .

这些在Command go: Maintaining module requirements中有详细说明:

If invoked with -mod=vendor, the go command loads packages from the main module's vendor directory instead of downloading modules to and loading packages from the module cache. The go command assumes the vendor directory holds correct copies of dependencies, and it does not compute the set of required module versions from go.mod files. However, the go command does check that vendor/modules.txt (generated by 'go mod vendor') contains metadata consistent with go.mod.

If invoked with -mod=mod, the go command loads modules from the module cache even if there is a vendor directory present.

If the go command is not invoked with a -mod flag and the vendor directory is present and the "go" version in go.mod is 1.14 or higher, the go command will act as if it were invoked with -mod=vendor.