咱們常常在使用CLI工具的時候,都會有這樣的參數輸出:git
➜ ~ 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 ➜ ~
能夠打印出構建時對應的版本信息,好比 Version,Go Version,Git Commit等,這個是如何實現的呢?github
主要是經過ldflags
參數來實如今構建的時候對變量進行賦值。docker
好比下面一段代碼:shell
package main import ( "flag" "fmt" "os" ) //須要賦值的變量 var version = "" //經過flag包設置-version參數 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") }
構建命令:segmentfault
go build -ldflags "-X main.version=v0.1" -o example
程序輸出:工具
➜ ./example version=v0.1
一、-ldflags build命令中用於調用接連接器的參數ui
-ldflags '[pattern=]arg list' arguments to pass on each go tool link invocation.
二、-X 連接器參數,主要用於設置變量this
-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.
這裏將version包單獨作了一個包存放,只須要引入便可:spa
package main import ( "flag" "github.com/go-demo/version" ) //經過flag包設置-version參數 var printVersion bool func init() { flag.BoolVar(&printVersion, "version", false, "print program build version") flag.Parse() } func main() { if printVersion { version.PrintVersion() } }
構建的shell以下(也能夠放在Makefile中):code
#!/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: 若是值內容中含有空格,能夠用單引號
最終版本輸出:
➜ 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
完整代碼:https://github.com/go-demo/ve...
本文在公衆號"學點程序"首發