Home > Enterprise >  Read go.mod and detect the version of project
Read go.mod and detect the version of project

Time:10-19

Mostly, go.mod file looks something like this :

module <module_name>

go 1.16

require (...)

Now, I want to extract the version value 1.16 in another golang project I read the file and stored it in a buffer.

buf, err := ioutil.ReadFile(goMODfile)
if err != nil {
    return false, err.Error()
}

I guess FindString() or MatchString() functions can help me out here, but I am not sure how !

CodePudding user response:

Instead of regexp you could just use "golang.org/x/mod/modfile" to parse the go.mod file's contents.

f, err := modfile.Parse("go.mod", file_bytes, nil)
if err != nil {
    panic(err)
}
fmt.Println(f.Go.Version)

https://play.golang.org/p/XETDzMcTwS_S


If you have to use regexp, then you could do the following:

re := regexp.MustCompile(`(?m)^go (\d \.\d (?:\.\d )?)$`)
match := re.FindSubmatch(file_bytes)
version := string(match[1])

https://play.golang.org/p/L5-LM67cvgP

  • Related