It’s good practice to include build version information and other metadata in an applications binary, since these are often useful for troubleshooting, monitoring and debugging purposes later on. As this information changes with each new build, maintaining these values in source code is not an option.

One possible solution to this problem is to use a link editor. Go’s linker supports setting a string variable under a given importpath (e.x. main.GitRef) using the -X flag. This flag can now be used to supply build information like the git reference from which the application is build to a know variable.

package main

import (
    "fmt"
)

var (
    // GitRef is supplied by the linker.
    GitRef string = "invalid:-use-ld-flags"
)

func main() {
    fmt.Printf("cmd gitref %s\n", GitRef)
}
gitref=$(git describe --tags --always --dirty)
go build -ldflags -X main.GitRef=${gitref}