go - 使用 'go build' 获取依赖项,即使它们位于 vendor/中

标签 go go-modules

我正在尝试获取 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 工具。

vendor如果 -mod=mod 指定了 go 版本,则仅自动使用文件夹(如果存在)(如果未使用 go.mod 另行指定)文件是 1.14或更高。

这些详细信息请参见 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.

关于go - 使用 'go build' 获取依赖项,即使它们位于 vendor/中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62685783/

相关文章:

go - 将 golang 应用程序部署到 Heroku 时运行迁移

go - 使用缓冲 IO 与使用 Goroutine 写入文件

mongodb - 如何更新文档中数组中的字段

go - 如何将 C.double 数组传递给 Cgo 函数?

go - 如何解决 Go 项目中嵌套应用程序二进制文件中的依赖项?

go - 如何在 go 模块上版本化和发布快照/未完成的工作?

Golang 模块使用

go - 相同依赖的两个版本 - 较低版本被忽略

api - beego 更新 & 通过 ID 获取 1

go - 如何在 Go 中计算随机数?