+++

Go -ldflags 增加编译版本

build

main.go

1package main
2
3import (
4	"os"
5	_ "gitea.linuxcrypt.cn/cli/version"
6)
7
8func main() {
9}

version/version.go

 1package version
 2
 3import "fmt"
 4
 5var (
 6	BUILD_VERSION string
 7	BUILD_DATE    string
 8	COMMIT_SHA1   string
 9)
10
11func init() {
12	fmt.Printf("BUILD_VERSION: %s, BUILD_DATE: %s, COMMIT_SHA1: %s\n", BUILD_VERSION, BUILD_DATE, BUILD_DATE)
13}

build

1go build -ldflags "-X gitea.linuxcrypt.cn/cli/version.BUILD_VERSION=0.0.1 -X gitea.linuxcrypt.cn/cli/version.BUILD_DATE=2023-01-04 -X gitea.linuxcrypt.cn/cli/version.COMMIT_SHA1=abc" -o ./bin/cli

输入-ldflags参数 ./bin/cli

 1BUILD_VERSION: 0.0.1, BUILD_DATE: 2023-01-04, COMMIT_SHA1: 2023-01-04
 2NAME:
 3   cli - CLI
 4
 5USAGE:
 6   cli [global options] [arguments...]
 7
 8VERSION:
 9   0.0.1
10
11GLOBAL OPTIONS:
12   --config value  (default: "config.yaml")
13   --help, -h      show help (default: false)
14   --version, -v   print the version (default: false)