当前位置:网站首页>go Cobra命令行工具入门
go Cobra命令行工具入门
2022-06-24 19:41:00 【虚幻私塾】
优质资源分享
| 学习路线指引(点击解锁) | 知识定位 | 人群定位 |
|---|---|---|
| 🧡 Python实战微信订餐小程序 🧡 | 进阶级 | 本课程是python flask+微信小程序的完美结合,从项目搭建到腾讯云部署上线,打造一个全栈订餐系统。 |
| Python量化交易实战 | 入门级 | 手把手带你打造一个易扩展、更安全、效率更高的量化交易系统 |
简介
Github:https://github.com/spf13/cobra
Star:26.5K
Cobra是一个用Go语言实现的命令行工具。并且现在正在被很多项目使用,例如:Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速的创建命令行工具,特别适合写测试脚本,各种服务的Admin CLI等。
比如 Mattermost 项目,就写了很多 Admin CLI:
为什么需要cobra
我们看一个简单的demo
使用前
| 123456789101112131415161718192021222324252627282930 | packagemain import(``"flag"``"fmt"``) funcmain() {``flag.Parse() args := flag.Args()``iflen(args) <= 0 {``fmt.Println(``"Usage: admin-cli [command]"``)``return``} switchargs[0] {``case"help"``:``// ...``case"export"``:``//...``iflen(args) == 3 { // 导出到文件``// todo``}elseiflen(args) == 2 { // 导出...``// todo``}``default``:``//...``}``} |
使用后
| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 | packagemain import(``"fmt"``"github.com/spf13/cobra"``"os"``) // rootCmd represents the base command when called without any subcommands``varrootCmd = &cobra.Command{``Use:"api"``,``Short:"A brief description of your application"``,``Long: A longer description ,``} // 命令一``varmockMsgCmd = &cobra.Command{``Use:"mockMsg"``,``Short:"批量发送测试文本消息"``,``Long: ``,``Run:func``(cmd *cobra.Command, args []string) {``fmt.Println(``"mockMsg called"``)``},``} // 命令二``varexportCmd = &cobra.Command{``Use:"export"``,``Short:"导出数据"``,``Long: ``,``Run:func``(cmd *cobra.Command, args []string) {``fmt.Println(``"export called"``)``},``} funcExecute() {``err := rootCmd.Execute()``iferr != nil {``os.Exit(1)``}``} funcinit() {``rootCmd.Flags().BoolP(``"toggle"``,"t"``, false,"Help message for toggle"``) rootCmd.AddCommand(mockMsgCmd)``rootCmd.AddCommand(exportCmd) exportCmd.Flags().StringP(``"out"``,"k"``,"./backup"``,"导出路径"``)``} funcmain() {``Execute()``} |
运行:
| 1234567891011121314151617 | $ go run main.go``A longer description Usage:``api [``command``] Available Commands:``completion Generate the autocompletion scriptforthe specified shell``export 导出数据``help Help about anycommand``mockMsg 批量发送测试文本消息 Flags:``-h, --help helpforapi``-t, --toggle Help messagefortoggle Use"api [command] --help"formoreinformation about acommand``. |
发现了吗?你不用再处理各种参数组合了,从此释放了出来,只需要写自己的业务逻辑即可!
基本概念
Cobra由三部分组成:
- 命令(Commands ):代表行为。命令是程序的中心点,程序的每个功能都应该可以通过命令进行交互,一个命令可以有任意个子命令。
- 参数(Args):命令的参数
- 标志(Flags):修饰命令。它修饰命令该如何完成。
官方推荐命令格式为:
| 1 | $ .``/appNamecommandargs --Flag |
如 hugo server --port=1313 :
- appName: hugo
- command: server
- flag: port
安装
Go pkg
添加依赖
| 1 | $ go get -u github.com``/spf13/cobra``@latest |
导入即可:
| 1 | import"github.com/spf13/cobra" |
命令行工具
建议安装命令行工具 cobra-cli ,以方便快速创建cobra项目,增加command等。
| 12 | # 命令行工具``$ goinstallgithub.com``/spf13/cobra-cli``@latest |
安装完成之后,执行 cobra-cli --help (请确保GOBIN已配置),输出下列信息则代表成功:
| 1234567891011121314151617181920212223 | $ cobra-cli --help``Cobra is a CLI libraryforGo that empowers applications.``This application is a tool to generate the needed files``to quickly create a Cobra application. Usage:``cobra-cli [``command``] Available Commands:``add Add acommandto a Cobra Application``completion Generate the autocompletion scriptforthe specified shell``help Help about anycommand``init Initialize a Cobra Application Flags:``-a, --author string author nameforcopyright attribution (default"YOUR NAME"``)``--config string configfile(default is $HOME/.cobra.yaml)``-h, --help helpforcobra-cli``-l, --license string name of licenseforthe project``--viper use Viperforconfiguration Use"cobra-cli [command] --help"formoreinformation about acommand``. |
入门实践
新建cobra命令行程序
安装了cobra-cli工具之后,执行 init 初始化创建项目:
| 1 | $ cobra-cli init |
此时,在当前目录自动生成如下文件:
| 1234 | ├── LICENSE``├── cmd``│ └── root.go``└── main.go |
main.go:
| 1234567 | packagemain import"tools/api/cmd" funcmain() {``cmd.Execute()``} |
| 1 | root.``go``(有删减): |
| 12345678910111213141516171819202122232425262728293031323334 | packagecmd import(``"fmt" "github.com/spf13/cobra"``) // rootCmd represents the base command when called without any subcommands``varrootCmd = &cobra.Command{``Use:"api"``,``Short:"A brief description of your application"``,``Long: A longer description ,``//Run: func(cmd *cobra.Command, args []string) {``// fmt.Println("api called")``//},``} // Execute adds all child commands to the root command and sets flags appropriately.``// This is called by main.main(). It only needs to happen once to the rootCmd.``funcExecute() {``err := rootCmd.Execute()``iferr != nil {``os.Exit(1)``}``} funcinit() {``// 全局flag``// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.api.yaml)") // local flag,暂不知道用处``rootCmd.Flags().BoolP(``"toggle"``,"t"``, false,"Help message for toggle"``)``} |
此时运行,不用指定参数,会执行rootCmd,打印使用说明:
| 12 | $ go build$ .``/api |
输出:
| 1234567891011121314 | A longer description Usage:``api [``command``] Available Commands:``completion Generate the autocompletion scriptforthe specified shell``help Help about anycommand Flags:``-h, --help helpforapi``-t, --toggle Help messagefortoggle Use"api [command] --help"formoreinformation about acommand``. |
命令构成
分析上面的默认输出:
- Available Commands:代表可以执行的命令。比如./api connect
- Flags:是参数。比如./api connect --ip=127.0.0.1:6379,–ip就是flag,127.0.0.1:6379就是flag的值。
新增命令
我们来新增一个命令试试,这也是命令行程序的魅力,通过不同的参数执行不同的动作。
语法:
| 1 | $ cobra-cli add [``command``] |
比如:
| 12 | $ cobra-cli add mock-msg``mockMsg created at/Users/xxx/repo/tools/api |
此时,在cmd下会多一个文件(mock_msg.go),内容如下:
| 1234567891011121314151617181920 | packagecmd import(``"fmt" "github.com/spf13/cobra"``) varmockMsgCmd = &cobra.Command{``Use:"mockMsg"``,``Short:"A brief description of your command"``,``Long: mock msg command,``Run:func``(cmd *cobra.Command, args []string) {``fmt.Println(``"mockMsg called"``)``},``} funcinit() {``rootCmd.AddCommand(mockMsgCmd)``} |
再执行rootCmd:
| 12 | $ go build``$ .``/api |
会发现,多了一个命令:
| 123456 | //...``Available Commands:``completion Generate the autocompletion scriptforthe specified shell``help Help about anycommand``mockMsg A brief description of yourcommand``//... |
执行mocMsg命令:
| 123 | $ .``/apimockMsg mockMsg called |
此时,就可以在生成的 mock_msg.go: Run() 函数中,放你自己的业务逻辑代码了。
如何显示自己的命令用法
上面新增了一个命令mockMsg,通过 ./api help 打印了命令和help,但是 Use 里面指定的内容打印到哪里去了呢?
这个时候,需要针对Command在指定help,此时就能打印这个命令的具体用法了。
| 12345678910 | .``/apimockMsg help``批量生产mq消息 Usage:``benchmark mockmsg [flags] Flags:``-g, --goroutine int32 并发routine数量 (default 1)``-h, --help helpformockmsg``-p, --packet int32 每个routine一秒写入mq的数量 (default 20) |
| 1 | -g和-p是新增的2个flag: |
| 123456 | funcinit() {``mockmsgCmd.Flags().Int32P(``"goroutine"``,"g"``, 1,"并发routine数量"``)``mockmsgCmd.Flags().Int32P(``"packet"``,"p"``, 20,"每个routine一秒写入mq的数量"``) rootCmd.AddCommand(mockmsgCmd)``} |
获取这2个值:
| 1234567891011 | // mockmsgCmd represents the mockmsg command``varmockmsgCmd = &cobra.Command{``Use:"mockmsg"``,``Short:"批量生产mq消息"``,``Run:func``(cmd *cobra.Command, args []string) {``// 这里要写全名``g, _ := cmd.Flags().GetInt32(``"goroutine"``)``p, _ := cmd.Flags().GetInt32(``"packet"``)``fmt.Println(``"mockmsg called,flags:g="``, g,",p="``, p,",args:"``, args)``},``} |
执行:
| 12 | $ go run main.go mockmsg -p 322 -g 5 args1 args2``mockmsg called,flags:g= 5 ,p= 322 ,args: [args1 args2] |
总结
我们通过一个例子,介绍了使用cobra带来的好处。通过一个完整的入门实践,演示了创建项目、添加命令和使用的一些示例,希望对你有所帮助!
参考:
边栏推荐
- Learn more about the practical application of sentinel
- C language operators and expressions
- Market trend report, technical innovation and market forecast of solar roof system in China
- STP spanning tree protocol Foundation
- Are you afraid of being asked MySQL related questions during the interview? This 30000 word essence summary + 100 interview questions, and it's enough to hang the interviewer
- High level application of SQL statements in MySQL database (II)
- 是否需要提高代码阅读能力?这有技巧
- vulnhub Vegeta: 1
- 糖豆人登录报错解决方案
- 2022安全员-B证考试题库及答案
猜你喜欢

The usage difference between isempty and isblank is so different that so many people can't answer it

ACL (access control list) basic chapter - Super interesting learning network

Learn more about redis' eight data types and application scenario analysis

Nuscenes -- remedies for missing image files or 0-size images encountered during dataset configuration

别再乱用了,这才是 @Validated 和 @Valid 的真正区别!!!

Win10 or win11 printer cannot print

【文本数据挖掘】中文命名实体识别:HMM模型+BiLSTM_CRF模型(Pytorch)【调研与实验分析】
See how sparksql supports enterprise level data warehouse

Programmers become gods by digging holes in one year, carrying flags in five years and becoming gods in ten years

Memory alignment of structures
随机推荐
vulnhub Vegeta: 1
Analyze the implementation process of oauth2 distributed authentication and authorization based on the source code
High level application of SQL statements in MySQL database (I)
开发规范~参数校验异常、异常返回提示切面
面试害怕被问MySQL相关问题 ?这份三万字精华总结 + 面试100 问,吊打面试官完全够了
源码阅读 | OpenMesh读取文本格式stl的过程
MySQL + JSON = King fried!!
CDN principle
动态菜单,自动对齐
2022年安全员-A证考题及答案
【Mongodb】READ_ME_TO_RECOVER_YOUR_DATA,数据库被恶意删除
ThreadLocal local thread
The usage difference between isempty and isblank is so different that so many people can't answer it
Visitor tweets tell you which groups are consuming blind boxes
In the multi network card environment, the service IP registered by Nacos is incorrect, resulting in inaccessible services
2022-06-16 工作记录--JS-判断字符串型数字有几位 + 判断数值型数字有几位 + 限制文本长度(最多展示n个字,超出...)
LeetCode Algorithm 剑指 Offer II 027. 回文链表
Can AI chat robots replace manual customer service?
The difference between interceptor and filter
Stop using it indiscriminately. This is the real difference between @validated and @valid!!!