如何在 Go 中导入并构建一组本地模块

How to import and build with a group of local modules in Go

我有以下文件:

$GOPATH/src/example.com
├── a
│   ├── a.go
│   └── go.mod
├── b
│   ├── b.go
│   └── go.mod
└── c
    ├── go.mod
    └── main.go

内容是:

a/a.go :

package a

func NewA() int {
    return 1
}

a/go.mod :

module example.com/a

go 1.17

b/b.go :

package b

import A "example.com/a"

func NewB() int {
    return A.NewA()
}

b/go.mod :

module example.com/b

go 1.17

replace example.com/a => ../a

require example.com/a v0.0.0-00010101000000-000000000000 // indirect

c/main.go :

package main

import "fmt"
import B "example.com/b"

func main() {
    fmt.Println(B.NewB())
}

c/go.mod :

module example.com/c

go 1.17

replace example.com/b => ../b

require example.com/b v0.0.0-00010101000000-000000000000 // indirect

go run main.goc 目录中时,我得到:

../b/b.go:3:8: missing go.sum entry for module providing package example.com/a (imported by example.com/b); to add:
        go get example.com/b@v0.0.0-00010101000000-000000000000

并且 go get example.com/b@v0.0.0-00010101000000-000000000000 表示:

go: downloading example.com/a v0.0.0-00010101000000-000000000000
example.com/b imports
        example.com/a: unrecognized import path "example.com/a": reading https://example.com/a?go-get=1: 404 Not Found

确定这是一个本地包,在 Internet 上不可用,它在所有必要的 go.mod 文件中使用 replace

如何使用本地包?

如果我将 example.com 重命名为 example 我得到:missing dot in first path element.

引用自Go Modules Reference: replace directive:

replace directives only apply in the main module’s go.mod file and are ignored in other modules. See Minimal version selection for details.

b/go.mod 中的 replace 指令在构建主包/模块时无效。您必须将该 replace 指令添加到主模块的 go.mod.

因此将其添加到 c/go.mod。在 c 文件夹中 运行 go mod tidy 之后,它看起来像这样:

module example.com/c

go 1.17

replace example.com/b => ../b

replace example.com/a => ../a

require example.com/b v0.0.0-00010101000000-000000000000

require example.com/a v0.0.0-00010101000000-000000000000 // indirect

如果 c/go.mod 中没有这个 replace,您会看到错误消息,因为 go 工具试图从 example.com(这是一个现有域)获取包,但它没有包含一个 go 模块。