Golang 在编译时使用ldflags动态设置包中变量的值

-X importpath.name=value
    Set the value of the string variable in importpath named name to value.
    Note that before Go 1.5 this option took two separate arguments.
    Now it takes one argument split on the first = sign.

参数作用

golang在编译、测试、安装时使用-ldflags -X动态设置包中变量的值
go install/build/test 时可以通过命令行参数设置package中的变量,
其格式为-X importpath.name=val, 其中importpath是变量所在包的的路径,
name是包中定义的变量, val 是需要在编译时设置的变量的值(string), 
name表示的变量只能是variable,不能是constant, 且不能通过函数调用的方式初始化,
其类型只能是string,不可是int, bool等.
如果val中存在空格,需要用引号括起来,如下date和go version输出结果有空格:
go build -ldflags "-X 'main.BUILD_TIME=`date`' -X 'main.GO_VERSION=`go version`'"
1
2
3
4
5
6
7
8
9
> docker version
Client: Docker Engine - Community
 Version:           19.03.3
 API version:       1.40
 Go version:        go1.12.10
 Git commit:        a872fc2
 Built:             Tue Oct  8 00:55:12 2019
 OS/Arch:           darwin/amd64
 Experimental:      false

编译时使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import "fmt"

var (
	version    string
	build_time string
	go_version string
	git_commit string
)

func main() {
	fmt.Println("version:", version)
	fmt.Println("go version:", go_version)
	fmt.Println("build time:", build_time)
	fmt.Println("git log:", git_commit)
}

执行输出:

1
2
3
4
5
6
> go build -ldflags "-X 'main.build_time=$(date)' -X 'main.git_commit=$(git log --pretty=format:"%h" -1)' -X main.version=1.0.0 -X 'main.go_version=`go version`'" main.go
> ./main
version: 1.0.0
go version: go version go1.14 darwin/amd64
build time: 2020年 8月 9日 星期日 19时09分50秒 CST
git log: 175a5eb

测试时使用

创建包和文件

1
2
> mkdir $GOPATH/src/gotest
> touch $GOPATH/src/gotest/go_test.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package gotest

import "testing"

var time string
var version string

func TestBuild(t *testing.T) {
  t.Log(time)
  t.Log(version)
}

执行输出:

1
2
3
4
5
6
7
8
> cd $GOPATH/src/
> GO111MODULE=off go test -ldflags="-X 'gotest.time=`date`' -X gotest.version=1.0.1" gotest -v
=== RUN   TestBuild
    TestBuild: go_test.go:9: 2020年 8月 9日 星期日 18时57分49秒 CST
    TestBuild: go_test.go:10: 1.0.1
--- PASS: TestBuild (0.00s)
PASS
ok      gotest  0.009s

参考