使用 Go 管理版本的方法示例
来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《使用 Go 管理版本的方法示例》,介绍一下管理版本,希望对大家的知识积累有所帮助,助力实战开发!
简介
如果你曾经运行过 docker version,
就会发现它提供了很多信息:
PS C:\Users\tzh> docker version Client: Docker Engine - Community Version: 19.03.4 API version: 1.40 Go version: go1.12.10 Git commit: 9013bf5 Built: Thu Oct 17 23:44:48 2019 OS/Arch: windows/amd64 Experimental: false Server: Docker Engine - Community Engine: Version: 19.03.4 API version: 1.40 (minimum version 1.12) Go version: go1.12.10 Git commit: 9013bf5 Built: Thu Oct 17 23:50:38 2019 OS/Arch: linux/amd64 Experimental: false containerd: Version: v1.2.10 GitCommit: b34a5c8af56e510852c35414db4c1f4fa6172339 runc: Version: 1.0.0-rc8+dev GitCommit: 3e425f80a8c931f88e6d94a8c831b9d5aa481657 docker-init: Version: 0.18.0 GitCommit: fec3683
对于编译好的二进制文件而言, 获取版本信息是非常重要的.
尽可能地提供详细信息, 有利于后期的维护和排错.
如何实现
对于版本信息等, 有两种方式,
一种从外部获取, 比如配置文件等,
另一种从源代码中获取, 将配置信息写死在源代码中.
这两种都不太好, 比如编译时间就不太好确定.
最好是能在 go build 时确定这些信息.
幸好, go build 提供了一个选项叫做 -ldflags '[pattern=]arg list'.
-X importpath.name=value Set the value of the string variable in importpath named name to value. This is only effective if the variable is declared in the source code either uninitialized or initialized to a constant string expression. -X will not work if the initializer makes a function call or refers to other variables. Note that before Go 1.5 this option took two separate arguments.
这使得我们可以在编译生成二进制文件时, 指定某些变量的值.
比如我们有个文件是 company/buildinfo 包的一部分.
package buildinfo var BuildTime string
运行 go build -ldflags="-X 'company/buildinfo.BuildTime=$(date)'" 会记录编译时间,
将 BuildTime 的值设置为编译时的时间, 即从 $(date) 中获取的时间.
参考:
Compile packages and dependencies
Command link
Including build information in the executable
实践
新增 pkg/version 包, 用于获取版本信息.
package version // 这些值应该是从外部传入的 var ( gitTag string = "" gitCommit string = "$Format:%H$" // sha1 from git, output of $(git rev-parse HEAD) gitTreeState string = "not a git tree" // state of git tree, either "clean" or "dirty" buildDate string = "1970-01-01T00:00:00Z" // build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ') )
package version import ( "fmt" "runtime" ) // 构建时的版本信息 type VersionInfo struct { GitTag string `json:"git_tag"` GitCommit string `json:"git_commit"` GitTreeState string `json:"git_tree_state"` BuildDate string `json:"build_date"` GoVersion string `json:"go_version"` Compiler string `json:"compiler"` Platform string `json:"platform"` } func (info VersionInfo) String() string { return info.GitTag } func Get() VersionInfo { return VersionInfo{ GitTag: gitTag, GitCommit: gitCommit, GitTreeState: gitTreeState, BuildDate: buildDate, GoVersion: runtime.Version(), Compiler: runtime.Compiler, Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH), } }
主要定义了一个结构体, 保持版本信息.
有些信息可以通过 runtime 获取, 有些是编译时传进来的.
这里没有明确的版本号, 而是使用 git tag 作为版本标签.
最后, 定义一个命令 version.
package cmd import ( "encoding/json" "fmt" "github.com/spf13/cobra" "tzh.com/web/pkg/version" ) var versionCmd = &cobra.Command{ Use: "version", Short: "Print the version info of server", Long: "Print the version info of server", Run: func(cmd *cobra.Command, args []string) { printVersion() }, } func printVersion() { info := version.Get() infoj, err := json.MarshalIndent(&info, "", " ") // 加一点缩进 if err != nil { fmt.Printf("遇到了错误: %v\n", err) } fmt.Println(string(infoj)) }
别忘了使用 AddCommand 添加子命令.
// 初始化, 设置 flag 等 func init() { cobra.OnInitialize(initConfig) rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "./conf/config.yaml", "config file (default: ./conf/config.yaml)") rootCmd.AddCommand(versionCmd) }
由此, 代码基本已经改完了, 还剩下最后一点, 修改 Makefile 文件,
以便简化操作过程.
修改 Makefile
SHELL := /bin/bash BASEDIR = $(shell pwd) # build with version infos versionDir = "tzh.com/web/pkg/version" gitTag = $(shell if [ "`git describe --tags --abbrev=0 2>/dev/null`" != "" ];then git describe --tags --abbrev=0; else git log --pretty=format:'%h' -n 1; fi) buildDate = $(shell TZ=UTC date +%FT%T%z) gitCommit = $(shell git log --pretty=format:'%H' -n 1) gitTreeState = $(shell if git status|grep -q 'clean';then echo clean; else echo dirty; fi) ldflags="-w -X ${versionDir}.gitTag=${gitTag} -X ${versionDir}.buildDate=${buildDate} -X ${versionDir}.gitCommit=${gitCommit} -X ${versionDir}.gitTreeState=${gitTreeState}" all: gotool build build: go build -ldflags ${ldflags} ./ run: go run -ldflags ${ldflags} ./ docker: go run -ldflags ${ldflags} ./ -c ./conf/config_docker.yaml
首行定义了运行的 shell, 默认是 /bin/sh, 这里改成了更常用的 /bin/bash.
然后, 就是定义了一大堆需要的参数.
在运行 go build 的时候添加了参数 -ldflags ${ldflags}.
如此, 以后只要使用 make build 就能生成具有版本信息的二进制文件了.
编译好之后, 可以运行 ./web version 查看具体的版本信息.
总结
通过为编译时添加额外信息, 可以生成更具交互性的二进制文件.
同时, 也能体会到 Makefile 带来的便捷.
当前部分的代码
作为版本 v0.12.0
本篇关于《使用 Go 管理版本的方法示例》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

- 上一篇
- 使用Go实现优雅重启服务功能

- 下一篇
- Go 高效截取字符串的一些思考
-
- Golang · Go教程 | 1小时前 |
- Golang静态文件服务配置教程
- 484浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Golang模块API文档生成教程
- 434浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Golang日志优化:异步缓冲提升效率
- 177浏览 收藏
-
- Golang · Go教程 | 2小时前 |
- GoChannel与队列选择指南
- 436浏览 收藏
-
- Golang · Go教程 | 2小时前 | defer recover
- Golangdefer与recover捕获goroutinepanic方法
- 472浏览 收藏
-
- Golang · Go教程 | 2小时前 |
- Golang运维工具与脚本编写技巧
- 387浏览 收藏
-
- Golang · Go教程 | 2小时前 |
- Golang事件监听实现观察者模式方法
- 356浏览 收藏
-
- Golang · Go教程 | 2小时前 |
- Go语言interface{}与类型安全技巧解析
- 231浏览 收藏
-
- Golang · Go教程 | 3小时前 |
- Golang定时器实现:Timer与Ticker对比详解
- 458浏览 收藏
-
- Golang · Go教程 | 3小时前 |
- Golang错误重试实现与策略详解
- 311浏览 收藏
-
- Golang · Go教程 | 3小时前 |
- Go语言实时读取日志技巧分享
- 293浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 515次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 499次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- AI Mermaid流程图
- SEO AI Mermaid 流程图工具:基于 Mermaid 语法,AI 辅助,自然语言生成流程图,提升可视化创作效率,适用于开发者、产品经理、教育工作者。
- 800次使用
-
- 搜获客【笔记生成器】
- 搜获客笔记生成器,国内首个聚焦小红书医美垂类的AI文案工具。1500万爆款文案库,行业专属算法,助您高效创作合规、引流的医美笔记,提升运营效率,引爆小红书流量!
- 816次使用
-
- iTerms
- iTerms是一款专业的一站式法律AI工作台,提供AI合同审查、AI合同起草及AI法律问答服务。通过智能问答、深度思考与联网检索,助您高效检索法律法规与司法判例,告别传统模板,实现合同一键起草与在线编辑,大幅提升法律事务处理效率。
- 837次使用
-
- TokenPony
- TokenPony是讯盟科技旗下的AI大模型聚合API平台。通过统一接口接入DeepSeek、Kimi、Qwen等主流模型,支持1024K超长上下文,实现零配置、免部署、极速响应与高性价比的AI应用开发,助力专业用户轻松构建智能服务。
- 900次使用
-
- 迅捷AIPPT
- 迅捷AIPPT是一款高效AI智能PPT生成软件,一键智能生成精美演示文稿。内置海量专业模板、多样风格,支持自定义大纲,助您轻松制作高质量PPT,大幅节省时间。
- 786次使用
-
- Golangmap实践及实现原理解析
- 2022-12-28 505浏览
-
- 试了下Golang实现try catch的方法
- 2022-12-27 502浏览
-
- 如何在go语言中实现高并发的服务器架构
- 2023-08-27 502浏览
-
- go和golang的区别解析:帮你选择合适的编程语言
- 2023-12-29 502浏览
-
- 提升工作效率的Go语言项目开发经验分享
- 2023-11-03 502浏览