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

浙公網安備 33010602011771號