Go 程序编译时添加 git 版本信息
Go 程序编译时添加 git 版本信息
通过 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
router.go:
import(
"myshop/app/version"
)
// ...
func init()
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