Embedding Data Into Go Programs
Discover how to embed git tags and build timestamps directly into your Go command-line programs during build time. This lesson teaches you to automate versioning within your binaries using go build flags, improving traceability and release management of your code. Additionally, learn to create build scripts to simplify this embedding process.
We'll cover the following...
Incorporating git tag for auto versioning
Versioning your code is a good practice. If you use a source control system like git, then you can tag commits using the git tag command. However, when you build your code, the program has no notion of the version of the source code it was built from.
One approach is to maintain a VERSION file or a version constant in your code and increment it every time you make a change. This is somewhat error-prone and redundant if you already tag your code.
Instead, we can embed the git tag automatically during build time. The key is to pass a -X option to -ldflags that specifies a package and variable in the program and the value.
$ go build -ldflags="-X '<package>.<variable>=<value>'"
To get the git tag during build time we can use the following command:
$ git describe --tags
v0.6
As long as we embed information we can ...