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

How to set package variable using -ldflags -X in Golang build – go如何在编译时用ldflags设置变量

如何在编译、安装、测试时动态设置变量,(增加版本号, 编译时间, Git Commit Hash等)

1
2
3
4
5
6
7
8
9
go tool link [flags] main.a

# Flags
-X importpath.name=value
Set the value of the string variable in importpath named name to value.
This is only effective if the variable is declared in the source code either uninitialized
or initialized to a constant string expression. -X will not work if the initializer makes
a function call or refers to other variables.
Note that before Go 1.5 this option took two separate arguments.

Including build information in the executable

The gc toolchain linker, cmd/link, provides a -X option that may be used to record arbitrary information in a Go string variable at link time. The format is -X importpath.name=val. Here importpath is the name used in an import statement for the package (or main for the main package), name is the name of the string variable defined in the package, and val is the string you want to set that variable to. When using the go tool, use its -ldflags option to pass the -X option to the linker.

Let’s suppose this file is part of the package company/buildinfo:

1
2
3
package buildinfo

var BuildTime string

You can build the program using this package using go build -ldflags="-X 'company/buildinfo.BuildTime=$(date)'" to record the build time in the string. (The use of $(date) assumes you are using a Unix-style shell.)

The string variable must exist, it must be a variable, not a constant, and its value must not be initialized by a function call. There is no warning for using the wrong name in the -X option. You can often find the name to use by running go tool nm on the program, but that will fail if the package name has any non-ASCII characters, or a " or % character.

golang在编译、测试、安装时使用-ldflags -X动态设置包中变量的值

go install/build/test 时可以通过命令行参数设置 package的变量, 其格式为-X importpath.name=val, 其中importpath是变量所在包的的路径, name是包中定义的变量, val 是需要在编译时设置的变量的值(string), 注意name表示的变量只能是变量(variable),不能是常量(constant), 且不能通过函数调用的方式初始化,其类型只能是string, 不可是int, bool等.

该方法在go install, go build, go test时均可以使用.

Example:

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)
}

用如下命令测试,其中date有空格,故而使用引号

1
go test  -ldflags="-X 'gotest.time=`date`' -X gotest.version=1.0.1" gotest -v

其输出如下:

1
2
3
4
5
6
=== RUN   TestBuild
--- PASS: TestBuild (0.00s)
build_test.go:9: Mon 5 Nov 18:06:13 CST 2018
build_test.go:10: 1.0.1
PASS
ok gotest 0.001s

Reference

打赏