Setting Package Variable When Building Go Project
Here’s a technique for setting a variable in a Go project when building it.
Say you have a global variable like the following:
// Package www.example.com/pkg/sample
package sample
var ServerVersion = “”
The server version is determined during build time based on the Git tag. This is available from the environment, but you don’t want to hard code this yourself. Doing so will mean that you’ll need to update it when it changes, and you know that you’ll forget to do that (I constantly do).
Previously what I tended to do is write a source code generator to set this, and just try to remember to run it when it changes. However, that is unnecessary:
What you can do is run go build
with the linker flag -X
:
$ go build -ldflags “-X www.example.com/pkg/sample.ServerVersion=1.2.0”
The variable needs to be of type string, and must be either uninitialised or initialised to a constant string expression.