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

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

主要定义了一个结构体, 保持版本信息.

有些信息可以通过 runtime 获取, 有些是编译时传进来的.

这里没有明确的版本号, 而是使用 git tag 作为版本标签.

最后, 定义一个命令 version.


package cmd

import (
  "encoding/json"
  "fmt"

  "github.com/spf13/cobra"
  "tzh.com/web/pkg/version"
)

var versionCmd = &cobra.Command{
  Use:  "version",
  Short: "Print the version info of server",
  Long: "Print the version info of server",
  Run: func(cmd *cobra.Command, args []string) {
    printVersion()
  },
}

func printVersion() {
  info := version.Get()
  infoj, err := json.MarshalIndent(&info, "", " ") // 加一点缩进
  if err != nil {
    fmt.Printf("遇到了错误: %vn", err)
  }
  fmt.Println(string(infoj))
}

别忘了使用 AddCommand 添加子命令.


// 初始化, 设置 flag 等
func init() {
  cobra.OnInitialize(initConfig)
  rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "./conf/config.yaml", "config file (default: ./conf/config.yaml)")
  rootCmd.AddCommand(versionCmd)
}

由此, 代码基本已经改完了, 还剩下最后一点, 修改 Makefile 文件,

以便简化操作过程.

修改 Makefile


SHELL := /bin/bash
BASEDIR = $(shell pwd)

# build with version infos
versionDir = "tzh.com/web/pkg/version"
gitTag = $(shell if [ "`git describe --tags --abbrev=0 2>/dev/null`" != "" ];then git describe --tags --abbrev=0; else git log --pretty=format:'%h' -n 1; fi)
buildDate = $(shell TZ=UTC date +%FT%T%z)
gitCommit = $(shell git log --pretty=format:'%H' -n 1)
gitTreeState = $(shell if git status|grep -q 'clean';then echo clean; else echo dirty; fi)

ldflags="-w -X ${versionDir}.gitTag=${gitTag} -X ${versionDir}.buildDate=${buildDate} -X ${versionDir}.gitCommit=${gitCommit} -X ${versionDir}.gitTreeState=${gitTreeState}"

all: gotool build
build:
  go build -ldflags ${ldflags} ./
run:
  go run -ldflags ${ldflags} ./
docker:
  go run -ldflags ${ldflags} ./ -c ./conf/config_docker.yaml

首行定义了运行的 shell, 默认是 /bin/sh, 这里改成了更常用的 /bin/bash.

然后, 就是定义了一大堆需要的参数.
在运行 go build 的时候添加了参数 -ldflags ${ldflags}.

如此, 以后只要使用 make build 就能生成具有版本信息的二进制文件了.

编译好之后, 可以运行 ./web version 查看具体的版本信息.

总结

通过为编译时添加额外信息, 可以生成更具交互性的二进制文件.
同时, 也能体会到 Makefile 带来的便捷.

当前部分的代码
作为版本 v0.12.0

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。