How the version number is automatically generated in the Golang code

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

In the past, when you wrote C + + code, you could predefine some version macro definitions in your code and then compile the data from outside as the version number. The Golang code does not support macro definitions, and if you hardcode the version information in your code each time, it can be laborious and easy to forget updates.

How to maintain the version number of the Golang program more elegantly?

After flipping through the Golang document, the following parameters are found in Go build

-ldflags 'flag list'    arguments to pass on each go tool link invocation.

Then found in the linker:

-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.

Follow the instructions in the documentation to set the linker parameters by-ldflags at build time. The value of the variable below the specified path is then modified by the linker-X.

According to this logic, we rewrite the following program:

package mainimport (      "fmt")var _VERSION_ = "unknown"func main() {      fmt.Printf("Version:[%s]\n", _VERSION_)}

Execute the following build command:

export TAG=dev-xxxx  go build -ldflags "-X main._VERSION_='$TAG'"  

When you execute the program, you can see the output of the predefined version number.

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.