Add info at build time to go binaries
31 Jul 2019Introduction
Sometimes it can be useful to capture information about your environment at build time, and have this information injected into the binary that you’re building. Some examples centre around versioning, where it might make sense to capture git commit hashes or build serials.
An example program
Two variables in this module gitCommit
, and buildSerial
are going to hold some version information for us. Running this program yields some rather uninteresting results.
-X switch
While building a program, you can use the -X
linker switch which will allow you to supply information into module variables from the build process.
We can obtain the latest build hash using git
with the following:
We can even synthesize a build number involving the date, perhaps?
Using the -ldflags
switch, we can now specify these at the console.
Closing up
Now that we have a binary built, it’s had its build information applied - these variables now magically receive these values.
Remember, these switches can be buried behid a Makefile
also, so you don’t need to be typing these things over and over.