[Golang] 编译程序时打上git提交信息标记
1、加入代码
//version.go
package version import ( "flag" "fmt" "os" ) var ( BuildVersion = "0.0" BuildTime = "0" CommitID = "xxxxx" ) func Parse() { var showVer bool flag.BoolVar(&showVer, "v", false, "show build version") flag.Parse() if showVer { fmt.Printf("build ver:\t%s\n", BuildVersion) fmt.Printf("build time:\t%s\n", BuildTime) fmt.Printf("Commit ID:\t%s\n", CommitID) os.Exit(0) } }
2、Makefile
BUILD_VERSION := $(SERVER_VERSION) BUILD_TIME := $(shell date "+%F %T") COMMIT_SHA1 := $(shell git rev-parse HEAD ) all myapp myapp: go build -gcflags "-N -l" \ -ldflags \ " \ -X 'version.BuildVersion=${BUILD_VERSION}' \ -X 'version.BuildTime=${BUILD_TIME}' \ -X 'version.CommitID=${COMMIT_SHA1}' \ " \ myapp
3、make
4、查看
./myapp -v