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

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

如何獲取 Go 模塊依賴項的路徑?

如何獲取 Go 模塊依賴項的路徑?

Go
繁花不似錦 2022-08-24 18:42:27
我有兩個Go模塊,讓我們將它們命名為.example.com/aexample.com/b讓它成為 :example.com/ago.modmodule example.com/ago 1.12require (  example.com/b v0.4.2)在 的根目錄中,有一個名為 的文件。 需要自動生成一些代碼作為其構建過程的一部分。此自動生成需要讀取 。example.com/bdata.yamlexample.com/adata.yaml我怎樣才能在查詢的目錄中為路徑讀取該文件?我知道下載后,模塊將位于某個地方,但我不知道如何從那里構造路徑,因為它包含一些不屬于導入路徑的字符。我希望有一些子命令或將輸出路徑,但我在文檔中沒有找到它。example.com/aexample.com/b(go env GOPATH)/pkg/mod!go modgo list我已經考慮過通過包含在Go代碼中(是的,我知道,但我現在不想需要Go 1.16),但是當我在編譯時需要它時,我只能在運行時訪問。data.yamlgo-bindata//go:embed
查看完整描述

2 回答

?
慕桂英546537

TA貢獻1848條經驗 獲得超10個贊

您可以像這樣與標志和標志一起使用:go list-m-f

go list -m -f '{{.Dir}}' example.com/b

旗幟:-m

導致 go list 列出模塊而不是包。在這種模式下,去列表的參數可以是模塊,模塊模式(包含...通配符)、版本查詢或特殊模式 all,它與構建列表中的所有模塊匹配。如果未指定任何參數,則列出主模塊。

(參考)

旗幟:-f

使用包模板的語法指定輸出的備用格式。使用標志時,傳遞給模板的結構為:-m

type Module struct {

    Path      string       // module path

    Version   string       // module version

    Versions  []string     // available module versions (with -versions)

    Replace   *Module      // replaced by this module

    Time      *time.Time   // time version was created

    Update    *Module      // available update, if any (with -u)

    Main      bool         // is this the main module?

    Indirect  bool         // is this module only an indirect dependency of main module?

    Dir       string       // directory holding files for this module, if any

    GoMod     string       // path to go.mod file for this module, if any

    GoVersion string       // go version used in module

    Error     *ModuleError // error loading module }


type ModuleError struct {

    Err string // the error itself

}


查看完整回答
反對 回復 2022-08-24
?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

您可以像這樣計算出模塊路徑:


package main


import (

    "fmt"

    "os"

    "path"


    "golang.org/x/mod/module"

)


func GetModulePath(name, version string) (string, error) {

    // first we need GOMODCACHE

    cache, ok := os.LookupEnv("GOMODCACHE")

    if !ok {

        cache = path.Join(os.Getenv("GOPATH"), "pkg", "mod")

    }


    // then we need to escape path

    escapedPath, err := module.EscapePath(name)

    if err != nil {

        return "", err

    }


    // version also

    escapedVersion, err := module.EscapeVersion(version)

    if err != nil {

        return "", err

    }


    return path.Join(cache, escapedPath+"@"+escapedVersion), nil

}


func main() {

    var path, err = GetModulePath("github.com/jakubDoka/mlok", "v0.4.7")

    if err != nil {

        panic(err)

    }


    if _, err := os.Stat(path); os.IsNotExist(err) {

        fmt.Println("you don't have this module/version installed")

    }

    fmt.Println("module found in", path)

}


查看完整回答
反對 回復 2022-08-24
  • 2 回答
  • 0 關注
  • 171 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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