go读取二进制文件编译信息
诉求
希望了解二进制文件编译时的信息
本地
可以通过go version -m ./binary查看:
$ go version -m ./go-pprof-practice
./go-pprof-practice: go1.24.2
path github.com/wolfogre/go-pprof-practice
mod github.com/wolfogre/go-pprof-practice v0.0.0-20230706085634-23c8f603cac9+dirty
build -buildmode=exe
build -compiler=gc
build DefaultGODEBUG=asynctimerchan=1,gotestjsonbuildtext=1,gotypesalias=0,httplaxcontentlength=1,httpmuxgo121=1,httpservecontentkeepheaders=1,multipathtcp=0,netedns0=0,panicnil=1,randseednop=0,rsa1024min=0,tls10server=1,tls3des=1,tlsmlkem=0,tlsrsakex=1,tlsunsafeekm=1,winreadlinkvolume=0,winsymlink=0,x509keypairleaf=0,x509negativeserial=1,x509rsacrt=0,x509usepolicies=0
build CGO_ENABLED=1
build CGO_CFLAGS=
build CGO_CPPFLAGS=
build CGO_CXXFLAGS=
build CGO_LDFLAGS=
build GOARCH=amd64
build GOOS=linux
build GOAMD64=v1
build vcs=git
build vcs.revision=23c8f603cac9cde2cf7533287fc2091c37dc024f
build vcs.time=2023-07-06T08:56:34Z
build vcs.modified=true
vsc为版本控制相关字段,包含提交哈希时间以及编译时源码是否修改。
网络
对于在线服务,希望将编译信息封装成api便于确认版本。
package main
import (
"fmt"
"runtime/debug"
"github.com/gin-gonic/gin"
)
func Info(c *gin.Context) {
info, ok := debug.ReadBuildInfo()
if !ok {
c.JSON(500, gin.H{"error": "no build info available"})
return
}
buildInfo := make(map[string]string)
for _, setting := range info.Settings {
buildInfo[setting.Key] = setting.Value
}
c.JSON(200, buildInfo)
}
func main() {
router := gin.Default()
router.GET("/info", Info)
fmt.Println("Server starting on :8080")
router.Run(":8080")
}
参考
Go1.18 新特性:编译后的二进制文件,将包含更多信息
debug package - runtime/debug - Go Packages

浙公网安备 33010602011771号