Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
add build info to go binary
package version

// reference: https://stackoverflow.com/questions/11354518/application-auto-build-versioning

import (
	"fmt"
	"runtime"
	"strings"
)

var (
	BinVersion     = "unknown"
	GitStatus      = "unknown"
	BuildTime      = "unknown"
	BuildGoVersion = "unknown"
)

func Print() string {
	return fmt.Sprintf("Version=%s\nGitStatus=%s\nBuildTime=%s\nBuildWith=%s\nRunOn=%s/%s\n",
		BinVersion, GitStatus, BuildTime, BuildGoVersion, runtime.GOOS, runtime.GOARCH)
}

func init() {
	if GitStatus == "" {
		GitStatus = "up to date"
	} else {
		GitStatus = strings.Replace(strings.Replace(GitStatus, "\r\n", " | ", -1), "\n", " | ", -1)
	}
}
# This how we want to name the binary output
BINARY=test

# values to pass for BinVersion, GitCommitLog, GitStatus, BuildTime and BuildGoVersion"
# Version=`git describe --tags`  # git tag 1.0.1  # require tag tagged before
Version=1.0.0
GitStatus=`git status -s`
BuildTime=`date +%FT%T%z`
BuildGoVersion=`go version`

# Setup the -ldflags option for build info here, interpolate the variable values
# notice: replace the path with your versionInfo module path
LDFLAGS=-ldflags "-w -s \
-X 'version.BinVersion=${Version}' \
-X 'version.GitStatus=${GitStatus}' \
-X 'version.BuildTime=${BuildTime}' \
-X 'version.BuildGoVersion=${BuildGoVersion}' \
"

install:
	go install ${LDFLAGS}

build:
	go build -o ${BINARY} ${LDFLAGS}

clean:
	if [ -f ${BINARY} ] ; then rm ${BINARY} ; fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment