Skip to content

Instantly share code, notes, and snippets.

@Harold2017
Created November 1, 2019 10:14
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Harold2017/2547c7f65fcdc93d2a6fe2f81319d301 to your computer and use it in GitHub Desktop.
Save Harold2017/2547c7f65fcdc93d2a6fe2f81319d301 to your computer and use it in GitHub Desktop.
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