This is a creation in Article, where the information may have evolved or changed.
We often see programs in the output of the program version, compile time, git commit ID and other information, such as Docker
ming@vultr:~$ docker versionClient: Version: 1.12.5 API version: 1.24 Go version: go1.6.4 Git commit: 7392c3b Built: Fri Dec 16 02:42:17 2016 OS/Arch: linux/amd64...
We can provide a configuration file version.conf
that is displayed when the program runs from the time it is version.conf
obtained. However, when deploying a program, it is not convenient to have additional configuration files in addition to the binaries.
or write this information into your code, which does not require additional version.conf
, but it is cumbersome to modify the code file every time you compile.
A better approach is to use the parameter-ldflags-x importpath.name=value at compile time, as the official explanation is as follows
-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 the separate arguments.
Now it takes one argument split on the first = sign.
The following code illustrates
package mainimport "fmt"var ( VERSION string BUILD_TIME string GO_VERSION string)func main() { fmt.Printf("%s\n%s\n%s\n", VERSION, BUILD_TIME, GO_VERSION)}
compile with the following command, note that because date
go version
the and output has spaces, it main.BUILD_TIME
main.GO_VERSION
must be enclosed in quotation marks .
go build -ldflags "-X main.VERSION=1.0.0 -X 'main.BUILD_TIME=`date`' -X 'main.GO_VERSION=`go version`'"
Run the program after compiling successfully, the result is as follows
ming@ubuntu:~/go_workspace/src/test$ ./test 1.0.0Sun Feb 12 00:13:27 CST 2017go version go1.7.5 linux/amd64