golang: 給二進位制檔案增加版本資訊

刘宏缔的架构森林發表於2024-11-23

一,程式碼:

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中

相關文章