Build Go Application with Version Information from Git

golang   programming   index

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

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 (

var (
	appver = "undefined"

func main() {

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().