Menu

Inject build-time variables with Golang

In this blog post I'm going to show you how to inject variables into your Golang executable at build-time. This is most useful for tagging your binary with a version or Git shasum or digest from version control.

Here's an example where the Docker project's CLI contains a commit ID of 77b4dce:

This is a great way to support your users - you can quickly and easily identify which build they are using and how old it could be.

Capture useful variable(s)

Before you get started, think about what makes sense to be injected at build-time? It could be anything from the hostname of the CI machine to the result of a web-service call or more commonly the last commit ID from your Git log.

Now this is just a minimal example to show you how to get started with Docker and Go build-time variables. You can take it further and optimize the size of the Docker image by using Multi-stage builds.

Here's an example of one of my Dockerfiles which builds a Golang application for a Raspberry Pi, MacOS and 64-bit Linux all in one file using multi-stage builds: