A practical guide to embedding version information into Go binaries using the `-ldflags -X` flag at build time. Covers injecting version strings, Git commit hashes, and build timestamps into package-level string variables without modifying source code. Includes setting up a dedicated version sub-package, adding a `--version` CLI flag, automating builds with a Makefile and GitHub Actions workflow, and exposing version info via an HTTP endpoint. Also compares the ldflags approach with `debug.ReadBuildInfo()` (Go 1.18+), highlighting trade-offs in portability, VCS dependency, and control.
Table of contents
IntroductionKey TakeawaysPrerequisitesUnderstanding the -X Linker FlagStep 1: Setting Up a Go Project for Version InjectionStep 2: Injecting Git Commit Hash and Build TimestampStep 3: Using ldflags with Packages Outside of mainStep 4: Automating Version Injection with a MakefileStep 5: Alternative Approach with debug.ReadBuildInfoComparison of Version Injection MethodsPractical Example: Exposing Version Info in an HTTP ServerFAQsConclusionSort: