Golang setting the value of a variable at compile time with Ldflags

Source: Internet
Author: User
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
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.