需求

golang程序在build时自动生成版本信息,使用 ./helloworld –version可以查看版本和build时间

实现原理

使用链接选项-X设置一个二进制文件中可以访问的变量

实例1

1
2
3
4
5
6
7
8
package main
import "fmt"

var Version = "No Version Provided"

func main() {
fmt.Println("HelloWorld Version is:", Version)
}
1
2
3
go run -ldflags "-X main.Version 1.5" helloworld.go

HelloWorld Version is: 1.5

实例2

1
2
3
4
5
6
7
8
9
10
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)
}
1
2
3
4
5
6
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

参考资料

golang-auto-build-versioning

Comments

2015-09-18