Inject values at build time in Go

Do you know that, It is possible to inject values to variables at build on Golang?

Let’s assume that you are building a command-line tool and you want to inject the latest build/commit hash to your application. Maybe you are building a rest API service and you want to add a deployed commit hash to your health check endpoint to see which build is running.

You have a package called version

package version

// CommitHash represents current build/commit hash.
var CommitHash string

Now build your project. Now we’ll use nm tool to find out symbols defined or used by an object file, archive, or executable. You can find more details about nm via go doc cmd/nm.

$ go build
$ go tool nm ./yourEXE | grep CommitHash

100444070 B # just an example output

Grab the full name; and

go build -ldflags="-X '$(git rev-parse HEAD)'"

Now the latest commit hash value is injected to version.CommitHash. This bash command git rev-parse HEAD returns the hash. This is just a string :)

You can inject whatever you want;

go build -ldflags="-X ''"

If you check go help build you’ll see;

-ldflags '[pattern=]arg list'
    arguments to pass on each go tool link invocation.

That’s it!

The original article can be found here.