Retrieving Module Versions from Within Go Code
The Go tooling includes module and dependency information within the compiled binary. Harnessing this feature, the runtime/debug.ReadBuildInfo() function presents a method to access this data while your application is executing. It furnishes an array containing dependency details, inclusive of module path and release number.
For each module or dependency, this array contains a debug.Module structure, detailed below:
type Module struct { Path string // module path Version string // module version Sum string // checksum Replace *Module // replaced by this module }
To exemplify this process:
package main import ( "fmt" "log" "runtime/debug" "github.com/icza/bitio" ) func main() { _ = bitio.NewReader bi, ok := debug.ReadBuildInfo() if !ok { log.Printf("Failed to read build info") return } for _, dep := range bi.Deps { fmt.Printf("Dep: %+v\n", dep) } }
When executed on the Go Playground, it yields the following output:
Dep: &{Path:github.com/icza/bitio Version:v1.0.0 Sum:h1:squ/m1SHyFeCA6+6Gyol1AxV9nmPPlJFT8c2vKdj3U8= Replace:<nil>}
Refer to the related question for further insights: How to acquire detailed Go build logs, along with all packages utilized in GOPATH and "go module" modes?
The above is the detailed content of How Can I Retrieve Module Versions from Within Go Code?. For more information, please follow other related articles on the PHP Chinese website!