debug.ReadBuildInfo Stamps CLI Version
debug.ReadBuildInfo reports the module path, Go version, and VCS revision so a CLI binary can print its own version information.
Code
package main
import (
"fmt"
"runtime/debug"
)
func main() {
info, ok := debug.ReadBuildInfo()
if !ok {
fmt.Println("build info unavailable")
return
}
// the CLI stamps its own version from build info
fmt.Println("module:", info.Main.Path)
fmt.Println("go version:", info.GoVersion)
if v := info.Main.Version; v != "" && v != "(devel)" {
fmt.Println("version:", v)
}
var vcs, revision string
for _, s := range info.Settings {
switch s.Key {
case "-ldflags":
fmt.Println("ldflags:", s.Value)
case "vcs":
vcs = s.Value
case "vcs.revision":
revision = s.Value
}
}
if vcs != "" && revision != "" {
fmt.Printf("vcs: %s %s\n", vcs, revision)
}
}How the snippet works
Everything that executes sits inside the function main.
Repetition is confined to for _, s := range info.Settings — the rest of the file is straight-line.
Caveats
- No install step: the snippet lives entirely inside the standard library.
Applying it
The signature doing the main work is func main()
Each step the file takes is announced in the output: build info unavailable, module:, go version:.
Statements that matter most here
for _, s := range info.Settings {
switch s.Key {
case "-ldflags":
fmt.Println("ldflags:", s.Value)
case "vcs":
vcs = s.Value
case "vcs.revision":
revision = s.Value
}
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does debug.ReadBuildInfo Stamps CLI Version print when run?
- Invoke the file as-is — the `build info unavailable`, `module:`, `go version:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.