Embedding Git commit hash in a Go binary

3 September 2022

This post will go over how to embed the Git commit hash inside a Go binary in order to support a /versionz endpoint. A /versionz could include multiple things, including manually defined version numbers, but another nice to have is the Git commit hash which produced the binary of the running software.

An example of doing this could be using a combination of GitHub actions to automate builds, Dockerfile, and Go’s ldflags build flags.

  1. Specify a Dockerfile build ARG variable for the Git commit hash.
  2. Inside GitHub actions build pipeline pass GITHUB_SHA ENV variable or github.sha context to the above Dockerfile build argument. Now the commit hash that triggered the build is available within the Dockerfile and go build context.
  3. Use go build with -ldflags to link the commit hash to a variable inside the binary.

Putting it all together:

Dockerfile:

...
ARG GIT_SHA
...

Inside the GitHub Actions definition pass the commit hash which triggered the build to GIT_SHA. Your build structure may vary, but the idea is the same. Here we use the github context.

...
docker-build-args = ... --build-arg GIT_SHA=${{ github.sha }} ...
...

Build the binary with -ldflags -X option:

RUN go build -ldflags="-X main.sha=${GIT_SHA}" cmd/my-project/main.go

After the build, inside main the variable sha is now set to the Git commit hash and available at runtime.

main.go

package main
...
// Gets set at build time via `-ldflags "-X main.sha=<value>"`
var sha = "local"
...

comments powered by Disqus