4 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超6個(gè)贊
在撰寫本文時(shí),我不知道有任何公開的 API。但是,查看源代碼,在Go mod 源文件go mod
中有一個(gè)功能非常有用
// 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

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超4個(gè)贊
嘗試這個(gè)?
package main
import (
"fmt"
"io/ioutil"
"os"
modfile "golang.org/x/mod/modfile"
)
const (
RED = "\033[91m"
RESET = "\033[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
}

TA貢獻(xiàn)1712條經(jīng)驗(yàn) 獲得超3個(gè)贊
如果您的起點(diǎn)是一個(gè)go.mod
文件并且您正在詢問如何解析它,我建議您從 開始 ,它以 JSON 格式go mod edit -json
輸出特定文件。
或者,您可以使用rogpeppe/go-internal/modfile,這是一個(gè)可以解析文件的 go 包,并且被rogpeppe/gohack和來自更廣泛社區(qū)的一些其他工具go.mod
使用。
Issue?#28101我認(rèn)為跟蹤向 Go 標(biāo)準(zhǔn)庫添加一個(gè)新的 API 來解析go.mod
文件。
以下是文檔的片段go mod edit -json
:
-json 標(biāo)志以 JSON 格式打印最終的 go.mod 文件,而不是將其寫回 go.mod。JSON 輸出對(duì)應(yīng)于這些 Go 類型:
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
}
這是 JSON 輸出的示例片段go mod edit -json,顯示了實(shí)際的模塊路徑(又名模塊名稱),這是您最初的問題:
{
? ? ? ? "Module": {
? ? ? ? ? ? ? ? "Path": "rsc.io/quote"
? ? ? ? },
在這種情況下,模塊名稱是rsc.io/quote.

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超8個(gè)贊
從 Go 1.12 開始(對(duì)于那些通過搜索找到它的人來說,他們使用的是模塊,但不一定是 OP 提到的舊版本),該runtime/debug
包包括獲取有關(guān)構(gòu)建的信息的功能,包括模塊名稱。例如:
import (
? ? "fmt"
? ? "runtime/debug"
)
func main() {
? ? info, _ := debug.ReadBuildInfo()
? ? fmt.Printf("info: %+v", info.Main.Path)
}
- 4 回答
- 0 關(guān)注
- 190 瀏覽
添加回答
舉報(bào)