golang: 给二进制文件增加版本信息
一,代码:
package main
import (
"embed"
"flag"
"github.com/gofiber/template/html/v2"
"net/http"
"fmt"
"runtime"
"industry/config"
"industry/routes"
)
// 构建版本信息
var (
Version = ""
GitCommit = ""
BuildTime = ""
)
func main() {
// 构建信息,golang版本 commit id 时间
var version bool
versionFlag := flag.Bool("version", false, "print version information and exit")
flag.BoolVar(&version, "v", false, "version")
flag.Parse()
if version || *versionFlag {
//"OS/Arch": runtime.GOOS + "/" + runtime.GOARCH,
fmt.Printf("App version: %s\ngo version: %s\nOS/Arch: %s\nGitCommit: %s\nBuild time: %s\n",
Version, runtime.Version(), runtime.GOOS + "/" + runtime.GOARCH, GitCommit, BuildTime)
return
}
二,测试效果:
$ go build -ldflags "-X main.Version=1.0.0 -X main.BuildTime=2024.11.23 -X main.GitCommit=b554659"
$ ./industry -v
App version: 1.0.0
go version: go1.23.3
OS/Arch: linux/amd64
GitCommit: b554659
Build time: 2024.11.23
$ ./industry --version
App version: 1.0.0
go version: go1.23.3
OS/Arch: linux/amd64
GitCommit: b554659
Build time: 2024.11.23
说明:build时的-ldflags参数,可以用脚本获取或者写入到Makefile中