登录
首页 >  Golang >  Go问答

获取 Go 模块的依赖路径的方法是什么?

来源:stackoverflow

时间:2024-02-21 22:54:23 165浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《获取 Go 模块的依赖路径的方法是什么?》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我有两个 go 模块,我们将它们命名为 example.com/aexample.com/b

让它成为 example.com/ago.mod

module example.com/a

go 1.12

require (
  example.com/b v0.4.2
)

example.com/b的根目录中,有一个名为data.yaml的文件。 example.com/a 需要自动生成一些代码作为其构建过程的一部分。此自动生成需要读取 data.yaml

如何在example.com/a目录中查询example.com/b的路径来读取该文件?我知道下载后,该模块将位于 (go env gopath)/pkg/mod 中的某处,但我不知道如何从那里构建路径,因为它包含一些 不属于导入路径的字符。我希望有一些 go modgo list 的子命令可以输出路径,但我在文档中没有找到它。

我考虑过通过 go-bindatadata.yaml 包含在 go 代码中(是的,我知道 //go:embed 但我现在不想要求 go 1.16),但随后我只需要当我在编译时需要时,可以在运行时访问。


正确答案


您可以将 go list-m 标志和 -f 标志一起使用,如下所示:

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

-m 标志:

导致 go list 列出模块而不是包。在此模式下, go list 的参数可以是模块、模块模式(包含 ...通配符)、版本查询或特殊模式 all,其中 匹配构建列表中的所有模块。如果没有指定参数, 主要模块已列出。

(reference)

-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
}

[上面的引用已根据上下文进行了更改]

(reference)

你可以这样算出模块路径:

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

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>