亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

獲取模塊名稱的API

獲取模塊名稱的API

Go
翻閱古今 2023-05-08 14:55:30
是否有 API 可以獲取使用 go 1.11 模塊系統的項目的模塊名稱?所以我需要從文件中的abc.com/a/m模塊定義中獲取。module abc.com/a/mgo.mod
查看完整描述

4 回答

?
紅糖糍粑

TA貢獻1815條經驗 獲得超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)


}

哪些輸出github.com/you/hello


查看完整回答
反對 回復 2023-05-08
?
繁花不似錦

TA貢獻1851條經驗 獲得超4個贊

嘗試這個?


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

}


查看完整回答
反對 回復 2023-05-08
?
交互式愛情

TA貢獻1712條經驗 獲得超3個贊

如果您的起點是一個go.mod文件并且您正在詢問如何解析它,我建議您從 開始 ,它以 JSON 格式go mod edit -json輸出特定文件。

或者,您可以使用rogpeppe/go-internal/modfile,這是一個可以解析文件的 go 包,并且被rogpeppe/gohack和來自更廣泛社區的一些其他工具go.mod使用。

Issue?#28101我認為跟蹤向 Go 標準庫添加一個新的 API 來解析go.mod文件。

以下是文檔的片段go mod edit -json

-json 標志以 JSON 格式打印最終的 go.mod 文件,而不是將其寫回 go.mod。JSON 輸出對應于這些 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,顯示了實際的模塊路徑(又名模塊名稱),這是您最初的問題:


{

? ? ? ? "Module": {

? ? ? ? ? ? ? ? "Path": "rsc.io/quote"

? ? ? ? },

在這種情況下,模塊名稱是rsc.io/quote.


查看完整回答
反對 回復 2023-05-08
?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

從 Go 1.12 開始(對于那些通過搜索找到它的人來說,他們使用的是模塊,但不一定是 OP 提到的舊版本),該runtime/debug包包括獲取有關構建的信息的功能,包括模塊名稱。例如:

import (

? ? "fmt"

? ? "runtime/debug"

)


func main() {

? ? info, _ := debug.ReadBuildInfo()

? ? fmt.Printf("info: %+v", info.Main.Path)

}


查看完整回答
反對 回復 2023-05-08
  • 4 回答
  • 0 關注
  • 192 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號