Application auto build versioning

The Go linker (go tool link) has an option to set the value of an uninitialised string variable:

-X importpath.name=value
  Set the value of the string variable in importpath named name to

value.
Note that before Go 1.5 this option took two separate arguments.
Now it takes one argument split on the first = sign.

As part of your build process, you could set a version string variable using this. You can pass this through the go tool using -ldflags. For example, given the following source file:

package main

import "fmt"

var xyz string

func main() {
    fmt.Println(xyz)
}

Then:

$ go run -ldflags "-X main.xyz=abc" main.go
abc

In order to set main.minversion to the build date and time when building:

go build -ldflags "-X main.minversion=`date -u +.%Y%m%d.%H%M%S`" service.go

If you compile without initializing main.minversion in this way, it will contain the empty string.

Leave a Comment