如何解决本地模块的传递依赖

How to resolve transitive dependencies of local modules

在某个随机文件夹中,有3个文件夹a、b、c。这些文件夹中的每一个都包含一个 mod 文件。

mod 个文件包含以下内容。

go.mod里面一个

module a

go 1.13

go.mod 里面 b

module b
go 1.13
require a v0.0.0
replace a v0.0.0 => ./../a

go.mod 内 c

module c
go 1.13
require b v0.0.0
replace b v0.0.0 => ./../b

模块 b 没有抛出错误。但是 module c 抛出错误

go: b@v0.0.0 requires
a@v0.0.0: unrecognized import path "a" (import path does not begin with hostname)

每个 module 的 module 名称中必须有一个点 (.)。

'Some random folder' 更改为 example.com。现在 example.com 命名文件夹包含所有 a.b.c 文件夹。 mod规则现在是这样的

模块 A 看起来像

module example.com/a
go 1.13

模块 B 看起来像

module example.com/b
go 1.13
require example.com/a v0.0.0
replace example.com/a v0.0.0 => ../a

模块 C 看起来像

module example.com/c
go 1.13
require example.com/b v0.0.0
replace example.com/b v0.0.0 => ../b

太糟糕了!错误!

go: example.com/b@v0.0.0 requires
example.com/a@v0.0.0: unrecognized import path "example.com/a" (https fetch: Get 
https://example.com/a?go-get=1: dial tcp 208.73.210.202:443: connect: connection refused)

本地 mod 规则的传递依赖如何工作? 为什么 Go 命中 example.com 来带来 mod 规则? 怎么回事?

Go Wiki: Modules: go.mod

exclude and replace directives only operate on the current (“main”) module. exclude and replace directives in modules other than the main module are ignored when building the main module. The replace and exclude statements, therefore, allow the main module complete control over its own build, without also being subject to complete control by dependencies. (See FAQ below for a discussion of when to use a replace directive).

还有 Command go: The main module and the build list:

The main module's go.mod file defines the precise set of packages available for use by the go command, through require, replace, and exclude statements. Dependency modules, found by following require statements, also contribute to the definition of that set of packages, but only through their go.mod files' require statements: any replace and exclude statements in dependency modules are ignored. The replace and exclude statements therefore allow the main module complete control over its own build, without also being subject to complete control by dependencies.

构建模块 c 时未找到包 a,因此 go 工具尝试解决它,尝试下载它。这就是为什么它试图将包名称解释为应该以主机名开头的名称。

您不需要将包 a 重命名为 example.com/a,但您必须在 cgo.mod 中添加 replace 指令告诉包 a 所在的位置。