golang — version injection

Mark Dawson
Mark Dawson
Published in
1 min readJan 2, 2017

--

Sometimes you want to have access to a version number inside your go application, for example you might have a command line app that supports a “-version” option which prints the current app version.

One way to do this is by using the go linker to inject the value into a variable in your code at compile time.

In the code below we have a variable called “version” which we simply print to the console:

package mainimport "fmt"var version stringfunc main() {
fmt.Println(version)
}

To set the “version” variable at build time, you specify the -ldflags option like so:

go install -ldflags "-X main.version=12345" cmd/myapp

This injects 12345 as the initial value to the “version” variable. You can make this more useful by using a date as your build value, or in some cases maybe you store the version in a file, in some of my projects I have a file called VERSION which contains a string like “1.5.9”, to inject that you can use the cat command to pipe it to the go command:

go install -ldflags "-X main.version=`cat ./VERSION`" cmd/myapp

--

--