Preface
In the past, when writing C/C++ code, some version macro definitions could be predefined in the code, and then data was passed from outside as the version number during compilation. golang code does not support macro definitions. If the version information is hardcoded in the code every time, it will be time-consuming and labor-intensive, and it will be easy to forget to update.
How to maintain the version number of golang program more elegantly?
After reading the golang document, find the following parameters in go build
-ldflags 'flag list' arguments to pass on each go tool link invocation.
Then inlinkerFound in:
-X =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.
According to the instructions in the document, when building, use -ldflags to set the parameters of the linker. Then use -X of the linker to modify the variable value below the specified path.
According to this logic, we rewrite the following program:
package main import ( "fmt" ) var _VERSION_ = "unknown" func main() { ("Version:[%s]\n", _VERSION_) }
Execute the following build command:
export TAG=dev-xxxx go build -ldflags "-X main._VERSION_='$TAG'"
When executing the program, you can see the output of the predefined version number.
Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.