Go工程打包版本号

Go工程打包版本号

有些项目,会把版本号写入源码中,每次升级都修改源码号。在 Go 项目中这不是好的处理方式。

一般情况下,可以通过 Git 获得版本信息,可以通过 shell 脚本实现,最后编译 Go 项目时,将版本信息通过 -X 链接参数传递进去:

// main.go
import (
	"fmt"
)

var Version string

func main() {
	fmt.Println("Version:", Version)
}
#!/bin/sh

version=""

if [ -f "VERSION" ]; then
    version=`cat VERSION`
fi

if [[ -z $version ]]; then
    if [ -d ".git" ]; then
        version=`shell git symbolic-ref HEAD | cut -b 12-)-$(shell git describe --tags --always --dirty --abbrev=7 2>/dev/null || echo dev`
    else
        version="unknown"
    fi
fi
CGO_ENABLED=0 go build -ldflags "-X example.com/main.Version=$version" main.go
# 最终版本号类似于 master-v1.0.4-2-ge5a4ce0-dirty
posted @ 2025-10-09 10:29  3的4次方  阅读(2)  评论(0)    收藏  举报