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.