获取模块名称的API

bsr*_*bsr 6 go go-modules

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

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

sse*_*lla 6

截至撰写本文时,我不知道有任何公开的 API。然而,查看源码, Go mod 源文件go mod中有一个非常有用的函数

// 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)

}
Run Code Online (Sandbox Code Playgroud)

哪个输出github.com/you/hello