To automatically add version information to a Go application, we can pass that information from git through build arguments.
This can be especially useful, if we are using git tags.
For example, the following will get the latest git tag, the last
commit hash, and whether there are locally modified uncommitted
(dirty) files.
$ git describe --always --long --dirty
v0.12.1-0-gca3521e-dirty
More information on the options are available with man git-describe.
To pass this information into our program, we can define a global variable, and assign it through build arguments.
So, define a variable appver in the main.
package main
import (
"fmt"
)
var (
appver = "undefined"
)
func main() {
fmt.Println(appver)
}
And build while assinging main.appver.
go build -ldflags="-X main.appver=$(git describe --always --long --dirty)" main.go
Same flags will work with go run.
Additionally, one can pass other variables like build time.
To get the version of Go itself, import "runtime" and get it with
runtime.Version().