When golang is compiled, ldflags is used to assign values to variables in the package to print version numbers and commits.
Many command line programs can output version information, commit, operating system and other information through the version parameter. The following introduces a method to print the version number of the command line program compiled by golang. The version information printed by docker: $ ~ docker versionClient: Docker Engine – Community Version: 18.09.2 API version: 1.39 Go version: go1.10.8 Git commit: 6247962 Built: Sun Feb 10 04:12:39 2019 OS/Arch: darwin/amd64 Experimental: false Server: Docker Engine – Community Engine: Version: 18.09.2 API version: 1.39 (minimum version 1.12) Go version: go1.10.6 Git commit: 6247962 Built: Sun Feb 10 04:13:06 2019 OS/Arch: linux/amd64 Experimental: false The implementation is to use a parameter of go build -ldflags. Enter go help build and you can see a configuration item: -ldflags ‘flag list’ arguments to pass on each go tool link invocation. This parameter is used to set some parameters of go link (static link). The specific parameters can be viewed through go tool link –help. The -X parameter can be assigned to variables in the package during compilation. Then we use the flag package to set the version parameter to print the version number. . main.go: package mainimport ( “flag” “log” “os “)var ( Version string…