Deliver - Software Engineering

Embed version and revision

When is this valuable? When publishing software for traceability and referenc. I.e. for bug reports or documentation reference. Your applications can use flags such as -v or -version for this purpose. One way to modify variables during the build is via -ldflags.

Using -ldflags

First declare a variable, not constant, in the main package.

var (
	version  = "0.0"
	revision = "dev"
)

func main() {
	var showVersion bool
	flag.BoolVar(&showVersion, "v", false, "print version and exit")

	if showVersion {
		fmt.Printf("%s", version)
		os.Exit(0)
	}
}

Then compile and change the version with

go build -ldflags "-X main.version=0.1" ./cmd/app

You can also change multiple values in this way, let's add the revision as well

go build -ldflags "-X main.version=0.1 -X main.revision=alpha" ./cmd/app