使用 Go 管理版本的方法示例

2020-01-28 14:39:00王振洲

简介

如果你曾经运行过 docker version,

就会发现它提供了很多信息:


PS C:Userstzh> docker version
Client: Docker Engine - Community
 Version:      19.03.4
 API version:    1.40
 Go version:    go1.12.10
 Git commit:    9013bf5
 Built:       Thu Oct 17 23:44:48 2019
 OS/Arch:      windows/amd64
 Experimental:   false

Server: Docker Engine - Community
 Engine:
 Version:     19.03.4
 API version:   1.40 (minimum version 1.12)
 Go version:    go1.12.10
 Git commit:    9013bf5
 Built:      Thu Oct 17 23:50:38 2019
 OS/Arch:     linux/amd64
 Experimental:   false
 containerd:
 Version:     v1.2.10
 GitCommit:    b34a5c8af56e510852c35414db4c1f4fa6172339
 runc:
 Version:     1.0.0-rc8+dev
 GitCommit:    3e425f80a8c931f88e6d94a8c831b9d5aa481657
 docker-init:
 Version:     0.18.0
 GitCommit:    fec3683

对于编译好的二进制文件而言, 获取版本信息是非常重要的.
尽可能地提供详细信息, 有利于后期的维护和排错.

如何实现

对于版本信息等, 有两种方式,

一种从外部获取, 比如配置文件等,

另一种从源代码中获取, 将配置信息写死在源代码中.

这两种都不太好, 比如编译时间就不太好确定.
最好是能在 go build 时确定这些信息.

幸好, go build 提供了一个选项叫做 -ldflags '[pattern=]arg list'.


-X importpath.name=value
  Set the value of the string variable in importpath named name to value.
  This is only effective if the variable is declared in the source code either uninitialized
  or initialized to a constant string expression. -X will not work if the initializer makes
  a function call or refers to other variables.
  Note that before Go 1.5 this option took two separate arguments.

这使得我们可以在编译生成二进制文件时, 指定某些变量的值.

比如我们有个文件是 company/buildinfo 包的一部分.


package buildinfo

var BuildTime string

运行 go build -ldflags="-X 'company/buildinfo.BuildTime=$(date)'" 会记录编译时间,

将 BuildTime 的值设置为编译时的时间, 即从 $(date) 中获取的时间.

参考:

Compile packages and dependencies
Command link
Including build information in the executable

实践

新增 pkg/version 包, 用于获取版本信息.


package version

// 这些值应该是从外部传入的
var (
  gitTag    string = ""
  gitCommit  string = "$Format:%H$"     // sha1 from git, output of $(git rev-parse HEAD)
  gitTreeState string = "not a git tree"    // state of git tree, either "clean" or "dirty"
  buildDate  string = "1970-01-01T00:00:00Z" // build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ')
)


package version

import (
  "fmt"
  "runtime"
)

// 构建时的版本信息
type VersionInfo struct {
  GitTag    string `json:"git_tag"`
  GitCommit  string `json:"git_commit"`
  GitTreeState string `json:"git_tree_state"`
  BuildDate  string `json:"build_date"`
  GoVersion  string `json:"go_version"`
  Compiler   string `json:"compiler"`
  Platform   string `json:"platform"`
}

func (info VersionInfo) String() string {
  return info.GitTag
}

func Get() VersionInfo {
  return VersionInfo{
    GitTag:    gitTag,
    GitCommit:  gitCommit,
    GitTreeState: gitTreeState,
    BuildDate:  buildDate,
    GoVersion:  runtime.Version(),
    Compiler:   runtime.Compiler,
    Platform:   fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH),
  }
}