Pay attention to the “learn some procedures” public account, know more dry goods content

When we use the CLI tool, we will have the following parameter output:

➜ ~ docker version Client: Docker Engine - Community version: 18.09.2 API version: 1.39 Go version: Git Commit: 6247962 Built: Sun Feb 10 04:12:39 2019 OS/Arch: Darwin/AMd64 Experimental:false
➜  ~
Copy the code

You can print the build Version information, such as Version, Go Version, Git Commit, etc. How to do this?

implementation

Variables are assigned at build time mainly through the LDFlags parameter.

For example, the following code:

package main

import (
	"flag"
	"fmt"
	"os"// The variable to be assigned var version =""// Set the -version parameter var through the flag packageprintVersion 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")}Copy the code

Build command:

go build -ldflags "- the main X. Version = v0.1" -o example
Copy the code

Program output:

➜. / example version = v0.1Copy the code

Parameters that

The -ldflags build command is used to call the linker

-ldflags '[pattern=]arg list'
	arguments to pass on each go tool link invocation.
Copy the code

2. -x linker parameter, mainly used to set variables

-X importpath.name=value
    Set the value of the string variable inImportpath 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.Copy the code

A complete example

The version package is stored as a separate package, which only needs to be imported:

package main

import (
	"flag"

	"github.com/go-demo/version") // Set the -version parameter var through the flag packageprintVersion bool

func init() {
	flag.BoolVar(&printVersion, "version".false."print program build version")
	flag.Parse()
}

func main() {
	if printVersion {
		version.PrintVersion()
	}
}
Copy the code

The shell is built as follows (which can also be placed in a 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
Copy the code

TIPS: Use single quotes if the value content contains Spaces

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
Copy the code

Full code: github.com/go-demo/ver…

This article was first published on the public account “Learn some procedures”

Pay attention to the public number, learn more about the relevant technical content!