I want to make sure that I can print out the version information from my Go builds. To do this I need to embed the current version information automatically into the application when I build it. Following the information at https://blog.alexellis.io/inject-build-time-vars-golang/ and this https://stackoverflow.com/questions/11354518/application-auto-build-versioning, I have the following boilerplate: This should go into the main package of the application:
var (
BuildVersion = ""
BuildTime = ""
GitHash = ""
GitBranch = ""
)
and in my func init()
:
printVersion := false
flag.BoolVar(&printVersion, "version", false, "Print the version")
flag.Parse()
if printVersion {
fmt.Printf("Git Branch: %s\n", GitBranch)
fmt.Printf("Git Hash: %s\n", GitHash)
fmt.Printf("Build Version: %s\n", BuildVersion)
fmt.Printf("Build Time: %s\n", BuildTime)
os.Exit(0)
}
The missing piece is the following Makefile
:
git_hash:=$(shell git rev-parse HEAD)
git_branch:=$(shell git rev-parse --abbrev-ref HEAD)
version=1.0.0
time:=$(shell /bin/date '+%Y-%m-%dT%H:%M')
SOURCES := $(shell find . -name '*.go')
ALL: app
app: $(SOURCES) Makefile
go build -ldflags="-X 'main.BuildTime=${time}' -X 'main.BuildVersion=${version}' -X 'main.GitHash=${git_hash}' -X 'main.GitBranch=${git_branch}'"