API获取模块名称

API to get the module name

是否有API获取使用go 1.11模块系统的项目的模块名称?

所以我需要从 go.mod 文件中的模块定义 module abc.com/a/m 中获取 abc.com/a/m

截至撰写本文时,我不知道有任何公开的 API。但是,查看 go mod 来源,有一个函数在 Go mod source file

中非常有用
// ModulePath returns the module path from the gomod file text.
// If it cannot find a module path, it returns an empty string.
// It is tolerant of unrelated problems in the go.mod file.
func ModulePath(mod []byte) string {
    //...
}

func main() {

    src := `
module github.com/you/hello

require rsc.io/quote v1.5.2
`

    mod := ModulePath([]byte(src))
    fmt.Println(mod)

}

输出github.com/you/hello

如果您的起点是一个 go.mod 文件并且您正在询问如何解析它,我建议您从 go mod edit -json 开始,它将在 [= 中输出一个特定的 go.mod 文件39=] 格式。这是文档:

https://golang.org/cmd/go/#hdr-Edit_go_mod_from_tools_or_scripts

或者,您可以使用 rogpeppe/go-internal/modfile, which is a go package that can parse a go.mod file, and which is used by rogpeppe/gohack 和来自更广泛社区的一些其他工具。

问题 #28101 我认为跟踪添加一个新的 API 到 Go 标准库来解析 go.mod 文件。

这是 go mod edit -json 的文档片段:

The -json flag prints the final go.mod file in JSON format instead of writing it back to go.mod. The JSON output corresponds to these Go types:

type Module struct {
    Path string
    Version string
}

type GoMod struct {
    Module  Module
    Go      string
    Require []Require
    Exclude []Module
    Replace []Replace
}

type Require struct {
    Path string
    Version string
    Indirect bool
}

这是 go mod edit -json 输出的 JSON 示例片段,它显示了实际的模块路径(又名模块名称),这是您最初的问题:

{
        "Module": {
                "Path": "rsc.io/quote"
        },

在本例中,模块名称为rsc.io/quote

试试这个?

package main

import (
    "fmt"
    "io/ioutil"
    "os"

    modfile "golang.org/x/mod/modfile"
)

const (
    RED   = "3[91m"
    RESET = "3[0m"
)

func main() {
    modName := GetModuleName()
    fmt.Fprintf(os.Stdout, "modName=%+v\n", modName)
}

func exitf(beforeExitFunc func(), code int, format string, args ...interface{}) {
    beforeExitFunc()
    fmt.Fprintf(os.Stderr, RED+format+RESET, args...)
    os.Exit(code)
}

func GetModuleName() string {
    goModBytes, err := ioutil.ReadFile("go.mod")
    if err != nil {
        exitf(func() {}, 1, "%+v\n", err)
    }

    modName := modfile.ModulePath(goModBytes)
    fmt.Fprintf(os.Stdout, "modName=%+v\n", modName)

    return modName
}

从 Go 1.12 开始(对于那些通过搜索找到它的人,他们使用的是模块,但不一定是 OP 提到的旧版本),runtime/debug 包包含获取构建信息的功能,包括模块名称。例如:

import (
    "fmt"
    "runtime/debug"
)

func main() {
    info, _ := debug.ReadBuildInfo()
    fmt.Printf("info: %+v", info.Main.Path)
}

您可以 运行 操场上的这个例子:https://go.dev/play/p/5oGbCRxSnjM

有关详细信息,请参阅 "runtime/debug".BuildInfo

的文档