25 February 2021

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.

Link to documentation


Previous post
Supporting HTTP/2 Without A tls.Conn In Go Go has support for both HTTP/1.x and HTTP/2 in the web server available in net/http. Unfortunately, in order support HTTP/2, the returned by the
Next post
Jira and Comments I’m going to claim that one of the biggest productivity sinks in software development is working with Jira. There’s so much to write about it. Today