Here's the proper way to add version information to Go binaries(as opossed to Version Your Go Binaries):
import "runtime/debug"
func getSetting(settings []debug.BuildSetting, k string) string {
for _, v := range settings {
if v.Key == k {
return v.Value
}
}
return ""
}
func printVersionInfo() {
bi, ok := debug.ReadBuildInfo()
if !ok {
panic("failed to read build info")
}
fmt.Println(bi.Main.Version)
fmt.Println(bi.GoVersion)
fmt.Println(getSetting(bi.Settings, "GOOS"))
fmt.Println(getSetting(bi.Settings, "GOARCH"))
fmt.Println(getSetting(bi.Settings, "vcs.revision"))
fmt.Println(getSetting(bi.Settings, "vcs.time"))
return nil
}
This is using the runtime/debug.ReadBuildInfo function to get the build information from the running binary and prints the:
Here's a sample output:
(devel)
go1.19
linux
amd64
78647c22ecd90761726ff4eacd8a9ff2e0a8ac51
2022-12-24T17:20:56Z
(devel)
will be replaced with the tag name if the binary was built from a tagged commit(e.g. go install my-package@v1.2.3
)
With this approach, you don't need to do anything besides calling ReadBuildInfo
and printing what you need.
This is a simpler and cleaner approach than the alternatives,
like setting variables at build time with -X
flag of -ldflags
or using embed
package.