程序开发 · 2023年12月9日

获取模块名称的API

当前位置: > > > > 获取模块名称的API

来源:stackoverflow
2024-04-23 13:45:33
0浏览
收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《获取模块名称的API》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

是否有API可以获取使用go 1.11模块系统的项目的模块名称?

所以我需要从 go.mod 文件中的模块定义 module abc.com/a/m 获取 abc.com/a/m

解决方案

截至撰写本文时,我不知道有任何公开的 api。然而,查看 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

试试这个?

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
}

今天关于《获取模块名称的API》的内容介绍就到此结束,如果有什么疑问或者建议,可以在公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!