--- title: "Set variables at build time in Golang" date: 2020-01-05T21:00:00Z tags: [golang, programming] draft: false --- For some CLI tools I use regularly I noticed that when I run the `version` flag get some version info that includes a git commit hash or a git tag to the command line: ```shell > kubectl version Client Version: version.Info{Major:"1", Minor:"16", GitVersion:"v1.16.3", GitCommit:"b3cbbae08ec52a7fc73d334838e18d17e8512749", GitTreeState:"clean", BuildDate:"2019-11-13T11:23:11Z", GoVersion:"go1.12.12", Compiler:"gc", Platform:"linux/amd64"} Server Version: version.Info{Major:"1", Minor:"16", GitVersion:"v1.16.2", GitCommit:"c97fe5036ef3df2967d086711e6c0c405941e14b", GitTreeState:"clean", BuildDate:"2019-10-15T19:09:08Z", GoVersion:"go1.12.10", Compiler:"gc", Platform:"linux/amd64"} ``` I discovered a nice way to do this for go programs. You can specify a value for a global variable at build time using the `-ldflags "-X"` flag. For this program: ```go package main import "fmt" var Version = "dev" func main(){ fmt.Printf("I'm version <%s>", Version) } ``` You can use this one liner that builds your go program while setting the *Version* variable to the *sha* hash of the latest commit. ```shell > go build -ldflags "-X main.Version=$(git rev-parse HEAD)" -o hello_app main.go > hello_app I'm version ba83f7c418c669f705a3cce0c58a1f9129a3de14 ``` Note that you have to specify the full path of the package in your project, for example: ```bash # Your project looks like # - main.go <- module `github.com/myrepo/test` # - version <- `github.com/myrepo/test/version` # - sha.go <- has `var Version = "dev"` > go build -ldflags "-X github.com/myrepo/test/version.Version=$(git rev-parse HEAD)" -o hello_app main.go > hello_app I'm version ba83f7c418c669f705a3cce0c58a1f9129a3de14 ```