Detail how to output version information in the Go project
- 2020-09-16 07:30:45
- OfStack
When we use the CLI tool, we often have the following parameter output:
➜ ~ docker version
Client: 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
➜ ~
You can print out the version information at build time, such as Version, Go Version, Git Commit, etc. How does this work?
implementation
The ldflags parameter is used to assign values to variables at the time of construction.
Take the following code:
package main
import (
"flag"
"fmt"
"os"
)
// Variables to assign to
var version = ""
// through flag Package is set -version parameter
var printVersion bool
func init() {
flag.BoolVar(&printVersion, "version", false, "print program build version")
flag.Parse()
}
func main() {
if printVersion {
println(version)
os.Exit(0)
}
fmt.Printf("example for print version")
}
Build command:
go build -ldflags "-X main.version=v0.1" -o example
Program output:
➜ ./example
version=v0.1
Parameters that
1. Parameters used to call the linker in the -ES30en build command
-ldflags '[pattern=]arg list'
arguments to pass on each go tool link invocation.
2. -ES35en linker parameter, mainly used to set variables
-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.
1 complete example
Here, version package is made into a separate package for storage. It only needs to be introduced:
package main
import (
"flag"
"github.com/go-demo/version"
)
// through flag Package is set -version parameter
var printVersion bool
func init() {
flag.BoolVar(&printVersion, "version", false, "print program build version")
flag.Parse()
}
func main() {
if printVersion {
version.PrintVersion()
}
}
shell is built as follows (you can also put it in Makefile) :
#!/bin/sh
version="v0.1"
path="github.com/go-demo/version"
flags="-X $path.Version=$version -X '$path.GoVersion=$(go version)' -X '$path.BuildTime=`date +"%Y-%m-%d %H:%m:%S"`' -X $path.GitCommit=`git rev-parse HEAD`"
go build -ldflags "$flags" -o example example-version.go
TIPS: If the value content contains Spaces, use single quotes
Final version output:
➜ sh build.sh
➜ ./example -version
Version: v0.1
Go Version: go version go1.13.1 darwin/amd64
Git Commit: a775ecd27c5e78437b605c438905e9cc888fbc1c
Build Time: 2020-01-09 19:01:51
Complete code: https: / / github com/go - demo/version