Go 程序编译时添加相关版本信息

通过 go build -ldflags "-X 'path/packageName.vername=value'" 的方式在编译时向程序中添加版本相关信息。

如:

app/version/version.go:

package version

var (
	BuildTime   = "N/A"
	GitCommitID = "N/A"
	GitBranch   = "N/A"
)

func GetVersion() map[string]string {
	return map[string]string{
		"build_time":    BuildTime,
		"git_commit_id": GitCommitID,
		"git_branch":    GitBranch,
	}
}

router.go:


import(
  "myshop/app/version"
)

// ...
func init() {
  service := instance.APIService()
	service.GET("version", func(c *gin.Context) {
		ver := version.GetVersion()
		data := make(map[string]interface{})
		for k, v := range ver {
			data[k] = v
		}
		ctr := api.Controller{}
		ctr.Succeed(c, data)
	})
}

build.sh:

#!/bin/bash

gitBranch=`git rev-parse --abbrev-ref HEAD`
gitCommit=`git log --pretty=format:"%h" -1`
buildTime=`date +%FT%T%z`
ldflags="-X 'myshop/app/version.BuildTime=${buildTime}' -X 'myshop/app/version.GitCommitID=${gitCommit}' -X 'myshop/app/version.GitBranch=${gitBranch}'"

binPath="bin/myshop_linux_amd64"

echo "start.."
GOOS=linux GOARCH=amd64 go build -o $binPath -ldflags "${ldflags}"
echo "compile completed."
echo "commit id: ${gitCommit}"
echo "branch: ${gitBranch}"
echo "buildTime: ${buildTime}"

echo "upx:"
upx -7 $binPath