Commit Hash from debug.ReadBuildInfo()

Commit Hash from debug.ReadBuildInfo()

(Jin Qing's Column, Jan., 2026)

To extract the vcs.revision from debug.ReadBuildInfo() in Go,

you need to iterate through the Settings slice in the BuildInfo struct and check for the key "vcs.revision".

This feature is available for binaries built with Go 1.18 or later, provided Git (or another supported VCS) was present during the build.

Here is a function that retrieves the vcs.revision string:

go 复制代码
package main

import (
	"fmt"
	"runtime/debug"
)

// GetVCSRecord retrieves the value for a given VCS key, e.g., "vcs.revision"
func GetVCSRecord(key string) string {
	if info, ok := debug.ReadBuildInfo(); ok {
		for _, setting := range info.Settings {
			if setting.Key == key {
				return setting.Value
			}
		}
	}
	return "" // Return empty string if not found or build info unavailable
}

func main() {
	commitHash := GetVCSRecord("vcs.revision")
	if commitHash != "" {
		fmt.Printf("VCS Revision: %s\n", commitHash)
	} else {
		fmt.Println("VCS Revision not available in build info.")
	}
}

Output example:

复制代码
VCS Revision: 70a1e4c86600385257a9c0b4f4c1899fe6edde8b

How to Use

  • Ensure Go Version: The code requires Go 1.18 or newer.
  • Build within a VCS repository: You must run go build from within a Git (or Mercurial, Fossil, Bazaar) repository for the information to be embedded.
  • Ensure VCS tool is present: The go build command needs access to the VCS tool (e.g., git) during the build process to populate the information.

Available VCS Keys

Besides "vcs.revision", other useful keys in info.Settings include:

  • "vcs": The version control system used (e.g., "git").
  • "vcs.time": The commit timestamp (e.g., "2022-01-15T16:47:19Z").
  • "vcs.modified": A boolean indicating if the source was modified since the last commit ("true" or "false").

(AI generated.)

相关推荐
十二同学啊29 分钟前
Go 工程化详解:项目结构、代码规范、测试体系与 CI/CD 实践
ci/cd·golang·代码规范
利威尔xu11 小时前
Go IM 源码实战(14):本地缓存快 3000 倍,失效却难 10 倍
后端·缓存·微服务·面试·golang
利威尔xu12 小时前
Go IM 源码实战(13):30 个会话只有 2 个红点,未读数错在三条路径
redis·后端·微服务·面试·golang
FungLeo13 小时前
成为全栈·Go 后端篇·从 Node SQLite 到 PostgreSQL:把迁移做成独立交付物
postgresql·golang·sqlite·go·数据库迁移·成为全栈
皓月盈江18 小时前
GO使用Gin框架实现模板定义、解析与渲染
linux·golang·go·gin·定义模板·解析模板·渲染模板
利威尔xu19 小时前
万字详解|Go 进阶(五):sync 包底层:Mutex 自旋 4 次转饥饿,WaitGroup 漏 1 个 Done 挂起 3000 goroutine
后端·golang·并发编程·源码分析·sync
日日大王学编程20 小时前
AI 时代后端方向新人的未来规划与看法
人工智能·后端·python·ai·golang
FungLeo20 小时前
成为全栈·Go 后端篇·Go 后端怎么测试:从成功响应到故障后置状态
golang·集成测试·差分测试·成为全栈·后端测试·数据库测试
Sw1zzle21 小时前
Go入门(零):Linux Ubuntu 22.04 安装 Go
linux·ubuntu·golang
码剑客1 天前
Gin+GORM+Redis 项目开发常见性能坑汇总(Go后端避坑指南)
redis·后端·golang·gin