代码之家  ›  专栏  ›  技术社区  ›  bsr

获取模块名称的API

  •  3
  • bsr  · 技术社区  · 6 年前

    有没有API来获取使用GO1.11模块系统的项目的模块名?

    abc.com/a/m 从模块定义 module abc.com/a/m 在里面 go.mod

    1 回复  |  直到 6 年前
        1
  •  4
  •   kataras    5 年前

    在撰写本文时,我还不知道有任何为此公开的api。但是 go mod Go mod source file

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

        2
  •  3
  •   thepudds    6 年前

    如果你的出发点是 go.mod 如果您正在询问如何解析它,我建议从 go mod edit -json ,输出特定的 转到.mod JSON格式的文件。以下是文档:

    https://golang.org/cmd/go/#hdr-Edit_go_mod_from_tools_or_scripts

    或者,你可以使用 rogpeppe/go-internal/modfile 转到.mod 文件,以及 rogpeppe/gohack

    问题 #28101 我认为是在Go标准库中添加了一个新的API来进行解析 文件夹。

    下面是一段 转到mod edit-json :

    json标志以json格式打印最终的go.mod文件,而不是 类型:

    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
    }
    

    转到mod edit-json 这显示了实际的模块路径(又名模块名),这是您最初的问题:

    {
            "Module": {
                    "Path": "rsc.io/quote"
            },
    

    在本例中,模块名为 rsc.io/quote

        3
  •  2
  •   Mohamed Bana    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
    }
    
    推荐文章