Go编译时变量注入
Go编译时变量注入
需求
golang程序在build时自动生成版本信息,使用 ./helloworld –version可以查看版本和build时间
实现原理
使用链接选项-X
设置一个二进制文件中可以访问的变量
package main
import "fmt"
var Version = "No Version Provided"
func main() {
fmt.Println("HelloWorld Version is:", Version)
}
go run -ldflags "-X main.Version=1.5" helloworld.go
HelloWorld Version is: 1.5
package main
import \"fmt\"
var buildstamp = \"no timestamp set\"
var githash = \"no githash set\"
func main() {
fmt.Println(\"HelloWorld buildstamp is:\", buildstamp)
fmt.Println(\"HelloWorld buildgithash is:\", githash)
}
go build -ldflags \"-X main.buildstamp=`date \'+%Y-%m-%d_%I:%M:%S\'` -X main.githash=`git rev-parse HEAD`\" helloworld.go
./helloworld
HelloWorld buildstamp is: 2015-09-08_05:58:49
HelloWorld buildgithash is: 1adb00d88d832687eb4148a3871829fb73021c29
Songzhibin