Retrieving Module Versions from Code in Go
In Go, the runtime/debug package provides access to detailed information about a program's dependencies and modules. This functionality enables you to retrieve and display module versions from within the code.
The debug.ReadBuildInfo() function returns a BuildInfo structure that contains a list of all imported dependencies. Each module or dependency is represented by a Module struct, which includes the following fields:
To retrieve and display the module versions, you can use code like this:
package main
import (
"fmt"
"log"
"runtime/debug"
)
func main() {
bi, ok := debug.ReadBuildInfo()
if !ok {
log.Printf("Failed to read build info")
return
}
for _, dep := range bi.Deps {
fmt.Printf("Module: %s, Version: %s\n", dep.Path, dep.Version)
}
}
This example will load the module and dependency information into a BuildInfo structure and iterate over the dependencies, printing out their paths and versions. You can modify this code to display the information in your desired format, such as the example in the question.
This approach avoids the need for using ldflags to set the versions externally. Instead, it relies on information provided by Go itself, making it a reliable and scalable solution for managing module versions.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3