How to Embed Version, Commit, and Build Time in Go Binaries at Build

Go developers can inject version metadata into binaries at build time using the -ldflags -X flag, which sets package-level string variables before compilation. The flag requires the full import path of the target variable, and silently does nothing if the path is incorrect, making precision essential. A common pattern involves a dedicated build package holding Version, Commit, and Time variables, populated via a Makefile using git describe, git rev-parse, and the current UTC timestamp. Since Go 1.18, the toolchain also automatically embeds VCS metadata such as commit hash and dirty state, accessible at runtime through the runtime/debug package without any extra flags. Together, these approaches give teams reliable version traceability, which proves critical during incidents when identifying exactly which binary is running in production.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in