golang中go.mod文件,做框架开发需要解析,请问如何解析?
go.mod解析可参考这个。做框架开发主要是用到require和replace。具体见代码。
go.mod文件如下:
module test5
go 1.17
require (
/gin-contrib/sse v0.1.0 // indirect
/gin-gonic/gin v1.7.7 // indirect
/go-playground/locales v0.14.0 // indirect
/go-playground/universal-translator v0.18.0 // indirect
/go-playground/validator/v10 v10.10.1 // indirect
/golang/protobuf v1.5.2 // indirect
/json-iterator/go v1.1.12 // indirect
/leodido/go-urn v1.2.1 // indirect
/mattn/go-isatty v0.0.14 // indirect
/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
/modern-go/reflect2 v1.0.2 // indirect
/ugorji/go/codec v1.2.7 // indirect
/x/crypto v0.0.0-20220307211146-efcb8507fb70 // indirect
/x/mod v0.5.1 // indirect
/x/sys v0.0.0-20220307203707-22a9840ba4d7 // indirect
/x/text v0.3.7 // indirect
/x/xerrors v0.0.0-20191204190536-9bdfabe68543 // indirect
google./protobuf v1.27.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
/emicklei/proto v1.9.1
)
replace /emicklei/proto v1.9.1 => /emicklei/proto v1.9.1
代码用golang编写。代码如下:
package main
import (
"fmt"
"io/ioutil"
"/x/mod/modfile"
)
func main() {
goModFilePathData, _ := ioutil.ReadFile("go.mod")
modFile, _ := modfile.Parse("go.mod", goModFilePathData, nil)
fmt.Println("require如下:")
fmt.Println("")
for _, r := range modFile.Require {
fmt.Println(r.Mod.Path + "@" + r.Mod.Version)
}
fmt.Println("------------------------")
fmt.Println("replace如下:")
fmt.Println("")
for _, r := range modFile.Replace {
fmt.Println("老:" + r.Old.Path + "@" + r.Old.Version)
fmt.Println("新:" + r.New.Path + "@" + r.New.Version)
fmt.Println("")
}
}
执行结果如下: