Build Time Go Variables

When building an application for distribution (even if only to other teams within an organization) it's sometimes handy to bake in some context from the build process (most often things like the Git commit hash, branch, etc.).

In the case of Go this can be achieved by using the CLI ldflags option's -X parameter. This allows for setting the value of an uninitialized (or initialized to a static string) variable when building an application, e.g. -ldflags package_name.var_name=value will set the variable var_name in package package_name to value.

Code example:

Go code using "version"

package main

var version string

func main() {
  println("Hello", version)
}

// Output: "Hello "
main.go

Build Script

#!/bin/bash

# Grab the latest commit hash
export GIT_COMMIT=`git rev-list HEAD -1`

# Run the Go program initializing "version" to the git hash
go run -ldflags="-X main.version=${GIT_COMMIT}" ./main.go

# Output: "Hello b9a4a8f277dde50022abedc3f2bcb60595555951"
build.sh
Matt Mohan

Matt Mohan

Toronto, Ontario, Canada