golang中一个优雅的开发和使用命令行工具的库 cobra

在go语言的命令行工具开发中,我们可以使用go官方的flags来解析用户输入参数实现命令行的开发, 但是如果是有涉及二级命令这类的开发用官方的这个flags就比较麻烦了, 今天给大家介绍一个可用帮助我们快速优雅的开发和使用命令行工具的库cobra, 他可以很轻松的实现二级命令的开发, 还可以帮我们自动生成使用帮助文档, 轻松定义命令执行前后的钩子等。 废话不多说,看示例:

package mainimport ("os""fmt""github.com/spf13/cobra" // 安装依赖 go get -u github.com/spf13/cobra/cobra
)// 这个是根命令定义
var rootCmd = &cobra.Command{Use:   "hugo",// 这个就是你的自己定义的根命令Short: "命令的简短说明",Long: `这里详细的说明你的命令的作用,更多信息 http://dev.tekin.cn`,Run: func(cmd *cobra.Command, args []string) {// Do Stuff Here},
}//定义一个参数
var Verbose bool// 子命令定义 运行方法 go run main.go version 编译后 ./hugo version
var versionCmd = &cobra.Command{Use:   "version", // Use这里定义的就是命令的名称Short: "Print the version number of Hugo",Long:  `All software has versions. This is Hugo's`,Run: func(cmd *cobra.Command, args []string) { //这里是命令的执行方法fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")},PreRun: func(cmd *Command, args []string){ //这个在命令执行前执行},PostRun: func(cmd *Command, args []string){ //这个在命令执行后执行},// 还有其他钩子函数 
}// 命令执行方法
func Execute() {//给我们定义的命令绑定参数 可以给我们定义的任何命令绑定参数rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")//将我们 定义的子命令添加到根命令中 使用方式  ./根命令 子命令rootCmd.AddCommand(versionCmd)// 1表示没有参数 ,设置一个默认的命令,这在你有多个命令,需要再没有任何参数的情况下设置一个默认的命令时非常有用if len(os.Args) == 1 { rootCmd.SetArgs([]string{"version"})}// 执行命令 如果异常会返回错误信息if err := rootCmd.Execute(); err != nil {fmt.Println(err)os.Exit(1)}
}//入口函数
func main() {Execute()
}

怎么样,用这个库来开发命令行工具是不是很惬意?   

github仓库地址 https://github.com/tekintian/go-cli-cobra

自定义命令Command结构体定义参考

这个里面定义了所有我们可以使用的属性和“方法”(类型为函数的属性)

// Command is just that, a command for your application.
// E.g.  'go run ...' - 'run' is the command. Cobra requires
// you to define the usage and description as part of your command
// definition to ensure usability.
type Command struct {// Use is the one-line usage message.Use string// Aliases is an array of aliases that can be used instead of the first word in Use.Aliases []string// SuggestFor is an array of command names for which this command will be suggested -// similar to aliases but only suggests.SuggestFor []string// Short is the short description shown in the 'help' output.Short string// Long is the long message shown in the 'help <this-command>' output.Long string// Example is examples of how to use the command.Example string// ValidArgs is list of all valid non-flag arguments that are accepted in bash completionsValidArgs []string// Expected argumentsArgs PositionalArgs// ArgAliases is List of aliases for ValidArgs.// These are not suggested to the user in the bash completion,// but accepted if entered manually.ArgAliases []string// BashCompletionFunction is custom functions used by the bash autocompletion generator.BashCompletionFunction string// Deprecated defines, if this command is deprecated and should print this string when used.Deprecated string// Hidden defines, if this command is hidden and should NOT show up in the list of available commands.Hidden bool// Annotations are key/value pairs that can be used by applications to identify or// group commands.Annotations map[string]string// Version defines the version for this command. If this value is non-empty and the command does not// define a "version" flag, a "version" boolean flag will be added to the command and, if specified,// will print content of the "Version" variable.Version string// The *Run functions are executed in the following order://   * PersistentPreRun()//   * PreRun()//   * Run()//   * PostRun()//   * PersistentPostRun()// All functions get the same args, the arguments after the command name.//// PersistentPreRun: children of this command will inherit and execute.PersistentPreRun func(cmd *Command, args []string)// PersistentPreRunE: PersistentPreRun but returns an error.PersistentPreRunE func(cmd *Command, args []string) error// PreRun: children of this command will not inherit.PreRun func(cmd *Command, args []string)// PreRunE: PreRun but returns an error.PreRunE func(cmd *Command, args []string) error// Run: Typically the actual work function. Most commands will only implement this.Run func(cmd *Command, args []string)// RunE: Run but returns an error.RunE func(cmd *Command, args []string) error// PostRun: run after the Run command.PostRun func(cmd *Command, args []string)// PostRunE: PostRun but returns an error.PostRunE func(cmd *Command, args []string) error// PersistentPostRun: children of this command will inherit and execute after PostRun.PersistentPostRun func(cmd *Command, args []string)// PersistentPostRunE: PersistentPostRun but returns an error.PersistentPostRunE func(cmd *Command, args []string) error// SilenceErrors is an option to quiet errors down stream.SilenceErrors bool// SilenceUsage is an option to silence usage when an error occurs.SilenceUsage bool// DisableFlagParsing disables the flag parsing.// If this is true all flags will be passed to the command as arguments.DisableFlagParsing bool// DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")// will be printed by generating docs for this command.DisableAutoGenTag bool// DisableFlagsInUseLine will disable the addition of [flags] to the usage// line of a command when printing help or generating docsDisableFlagsInUseLine bool// DisableSuggestions disables the suggestions based on Levenshtein distance// that go along with 'unknown command' messages.DisableSuggestions bool// SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.// Must be > 0.SuggestionsMinimumDistance int// TraverseChildren parses flags on all parents before executing child command.TraverseChildren bool//FParseErrWhitelist flag parse errors to be ignoredFParseErrWhitelist FParseErrWhitelist// commands is the list of commands supported by this program.commands []*Command// parent is a parent command for this command.parent *Command// Max lengths of commands' string lengths for use in padding.commandsMaxUseLen         intcommandsMaxCommandPathLen intcommandsMaxNameLen        int// commandsAreSorted defines, if command slice are sorted or not.commandsAreSorted bool// commandCalledAs is the name or alias value used to call this command.commandCalledAs struct {name   stringcalled bool}// args is actual args parsed from flags.args []string// flagErrorBuf contains all error messages from pflag.flagErrorBuf *bytes.Buffer// flags is full set of flags.flags *flag.FlagSet// pflags contains persistent flags.pflags *flag.FlagSet// lflags contains local flags.lflags *flag.FlagSet// iflags contains inherited flags.iflags *flag.FlagSet// parentsPflags is all persistent flags of cmd's parents.parentsPflags *flag.FlagSet// globNormFunc is the global normalization function// that we can use on every pflag set and children commandsglobNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName// usageFunc is usage func defined by user.usageFunc func(*Command) error// usageTemplate is usage template defined by user.usageTemplate string// flagErrorFunc is func defined by user and it's called when the parsing of// flags returns an error.flagErrorFunc func(*Command, error) error// helpTemplate is help template defined by user.helpTemplate string// helpFunc is help func defined by user.helpFunc func(*Command, []string)// helpCommand is command with usage 'help'. If it's not defined by user,// cobra uses default help command.helpCommand *Command// versionTemplate is the version template defined by user.versionTemplate string// inReader is a reader defined by the user that replaces stdininReader io.Reader// outWriter is a writer defined by the user that replaces stdoutoutWriter io.Writer// errWriter is a writer defined by the user that replaces stderrerrWriter io.Writer
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/20014.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

汇舟问卷:国外问卷调查两小时赚28美金?

现在的年轻人不愿意打工的原因不只是因为累&#xff0c;而且赚的钱也不多。有些人开玩笑地说&#xff0c;摆个摊儿卖点小商品都比上班赚得多&#xff0c;这确实是事实。 打工只能勉强维持生计&#xff0c;不能致富。因此&#xff0c;如果我们想赚大钱&#xff0c;首先需要改变…

炫云亮相第二十届中国国际动漫节国际动漫游戏商务大会!

5月28日-29日&#xff0c;备受瞩目的第二十届中国国际动漫节国际动漫游戏商务大会(iABC2024)在杭州滨江开元名都大酒店隆重召开&#xff01;本届大会以动漫IP为核心&#xff0c;从源头到全系列数字内容&#xff0c;探索创新协同、融合发展、价值转化&#xff0c;并对重点作品和…

IDEA 常用技巧

1、代码块整体移动 选中&#xff0c;tab整体右移选中&#xff0c;shifttab整体左 移 2、统一修改变量 3.方法分割线 seting >> editor >> apperance >> show method separators 4、快捷键 构造器、set与get方法、方法重写、toString 等快捷操 鼠标停留在…

人工智能在消化道肿瘤中的最新研究【24年五月|顶刊速递·05-31】

小罗碎碎念 2024-05-31|医学AI顶刊速递 今天分享的六篇文章,主题是AI+结肠癌。但是,并非所有的文章都是直接与结直肠癌相关,比如第一篇研究的就是肝癌。 我其实想关注的是消化道肿瘤的医学AI研究——消化道由口腔、食管、胃、小肠、大肠和直肠组成,而肝脏虽然不直接参与食…

java海滨学院班级回忆录源码(springboot)

风定落花生&#xff0c;歌声逐流水&#xff0c;大家好我是风歌&#xff0c;混迹在java圈的辛苦码农。今天要和大家聊的是一款基于springboot的海滨学院班级回忆录。项目源码以及部署相关请联系风歌&#xff0c;文末附上联系信息 。 项目简介&#xff1a; 海滨学院班级回忆录的…

运维开发.Kubernetes探针与应用

运维系列 Kubernetes探针与应用 - 文章信息 - Author: 李俊才 (jcLee95) Visit me at CSDN: https://jclee95.blog.csdn.netMy WebSite&#xff1a;http://thispage.tech/Email: 291148484163.com. Shenzhen ChinaAddress of this article:https://blog.csdn.net/qq_28550263…

量子计算:未来技术的变革与应用

量子计算&#xff1a;未来技术的变革与应用 引言 量子计算是近年来科学技术领域的一个前沿话题&#xff0c;它有潜力彻底改变我们处理信息的方式。通过利用量子力学的独特性质&#xff0c;量子计算机可以在某些问题上超越传统计算机的性能&#xff0c;带来计算能力的巨大飞跃…

2024 江苏省大学生程序设计大赛 2024 Jiangsu Collegiate Programming Contest(FGKI)

题目来源&#xff1a;https://codeforces.com/gym/105161 文章目录 F - Download Speed Monitor题意思路编程 G - Download Time Monitor题意思路编程 K - Number Deletion Game题意思路编程 I - Integer Reaction题意思路编程 写在前面&#xff1a;今天打的训练赛打的很水&…

电商物流查询解决方案助力提升消费者体验

截至2023年12月&#xff0c;中国网络购物用户规模达9.15亿人&#xff0c;占网民整体的83.8%。这一庞大的数字不仅展现了电子商务的蓬勃发展&#xff0c;也标志着数字零售企业营销战略的转变——从以产品和流量为核心&#xff0c;到用户为王的新阶段。因此&#xff0c;提升消费者…

探索 Android Studio 中的 Gemini:加速 Android 开发的新助力

探索 Android Studio 中的 Gemini&#xff1a;加速 Android 开发的新助力 在 Gemini 时代的下一篇章中&#xff0c;Gemini融入了更多产品中&#xff0c;Android Studio 正在使用 Gemini 1.0 Pro 模型&#xff0c;使 Android 开发变得更快、更简单。 Studio Bot 现已更名为 And…

广告联盟项目:广告收益小游戏app开发

开发一个基于广告联盟项目的广告收益小游戏APP涉及多个关键步骤和考虑因素。以下是一个大致的开发流程和要点&#xff1a; 市场调研与定位&#xff1a; 深入了解目标用户群体&#xff0c;包括他们的游戏偏好、使用习惯以及广告接受度1。 分析市场上类似产品的成功与失败案例&…

js中的遍历(for、forEach、map、filter、reduce、every、some、includes、find)

js中的遍历 1. for 和 forEach性能上的比较&#xff1a;for性能更优异步同步化的支持度&#xff1a;for支持&#xff0c;forEach不支持 2. map用法1&#xff1a;将数组内每个元素2后&#xff0c;获取新数组用法2&#xff1a;将数组对象内每个元素的名称拿出来&#xff0c;作为一…

Linux服务升级:Twemproxy 升级 Redis代理

目录 一、实验 1.环境 2.多实例Redis部署 3.Twemproxy 升级Redis代理 一、实验 1.环境 &#xff08;1&#xff09;主机 表1 主机 系统版本软件IP备注CentOS7.9Twemproxy192.168.204.200 Redis代理 Redis127.0.0.1:6379第一个Redis实例 Redis127.0.0.1:6380第二个…

微信小程序-页面导航-导航传参

1.声明式导航传参 navigator组件的url属性用来指定将要跳转到的页面的路径&#xff0c;同时&#xff0c;路径的后面还可以携带参数&#xff1a; &#xff08;1&#xff09;参数与路径之间使用 ? 分割 &#xff08;2&#xff09;参数键与参数值用 相连 &#xff08;3&…

Ubuntu开机提示fsck exited with status code 4的解决办法

目录 Ubuntu开机提示fsck exited with status code 4的解决办法 这是因为关机不当导致磁盘内的数据损坏 U

五星级可视化大屏(02):再发一波,纯数据图表也跟效果杠杠的。

这是第一期&#xff0c;分享纯数据图表的&#xff0c;请大家仔细观看。

记录一次前端页面崩溃的产生及处理

记录一次前端页面崩溃的产生及处理 ​  起因&#xff1a;前端的一个地图页面某一些单子一点进去&#xff0c;就会导致页面卡死、崩溃&#xff0c;浏览器最终给的错误码为&#xff1a;out of memory。 ​  排查&#xff1a;OOM&#xff01;第一反应是猜测会不会是因为地图要…

华为云的云主机安装的linux系统不能使用yum下载软件包、程序、组件等

目录 一、背景介绍 二、问题描述 1、尝试使用yum安装traceroute 2、更换yum源 3、使用curl命令访问百度&#xff0c;测试网络 三、问题分析和解决 1、修改网卡设置 &#xff08;1&#xff09;ifconfig查看网卡信息 &#xff08;2&#xff09;添加DNS 2、修改/etc/res…

移动机器人传感器

移动机器人传感器是机器人系统的关键组成部分&#xff0c;用于感知和理解周围环境&#xff0c;为导航、避障、定位和任务执行提供必要的信息。以下是一些常用的移动机器人传感器及其功能和应用。 常用移动机器人传感器 激光雷达 (LiDAR)摄像头深度摄像头超声波传感器红外传感器…

idea 插件推荐

idea 插件推荐 RESTFul-Tool 接口搜索Show Comment 代码注释展示translation 翻译(注释翻译)MyBatisCodeHelperPro 日志封装sql xml跳转GitToolBox 展示GIT提交Jenkins Control idea jenkins 集成Gitmoji Plus: Commit Button GIT提交moji表情 RESTFul-Tool 接口搜索 https://…