cobra开源地址

https://github.com/spf13/cobra

cobra是什么

Cobra is a library for creating powerful modern CLI applications.

Cobra is used in many Go projects such as Kubernetes, Hugo, and GitHub CLI to name a few. This list contains a more extensive list of projects using Cobra.

cobra是用来创建先进现代化命令行工具的库。k8s/Hugo/Github Cli/Frp都是用cobra创建的。

cobra-cli

cobra-cli可以生成对应命令的代码,遵循cobra要求的代码风格和模式。如下的代码示例就是使用cobra-cli来进行的

基本概念

  • Command:命令。通过命令告知程序应该做什么。
    示例:
    docker ps
    docker images
    docker build -t tony/mes:v1 .
    docker run -d -p 10000:1000 tony/mes:v1
    ps/images/build/run均为命令
  • Flag:参数值,字段值。有时候,想让程序干一件事情,光命令是不够的,还需要指定一些参数。这些参数叫做Flag。Flag属于某个命令或者根命令。Flag是对命令的补充,不同的命令下可以有相同的Flag
    示例:
    docker build -t tony/mes:v1
    docker run -d -p 10000:10000
    docker run -d --port 10000:10000
    docker -h
    docker --help
    hugo server --port=1313
    flag通常是-或者--开头,有的有值,有的没有值,是对Command的补充。

上手代码

比如我想写一个API程序,名字叫cobratest,使用命令指定如下功能

  • 启动配置(serve)

    • 监听的ip(例如:--ip=127.0.0.1)
    • 监听port(例如:--port=2000 或者 -p=2000)
  • 日志配置(log)
    • 日志路径(例如:--directory=c:/log 或者 -d=c:/log)
    • 日志级别(例如:-level=trace 或者 -l=trace)
  • 数据库配置(db)
    • 数据库的类型(例如:--type=mysql或者-t=mysql)
    • 连接字符串(例如:--string=xxx或者-s=xxx)
      程序启动起来大概是这样的命令
cobratest serve --ip=0.0.0.0 --port 10000
cobratest log --directory=d:/log --level=info
cobratest db --type=mysql --string=xxx

或者

cobratest serve --ip=0.0.0.0 -p 10000
cobratest log -d=d:/log -l=info
corbratest db -t=mysql -s=xxx

上述有三个cobra中的命令:

  • serve
  • log
  • db

开始撸码

新建一个cobratest文件夹,新建一个main.go文件

初始化go module:

go mod init cobratest

安装cobra-cli

go install github.com/spf13/cobra-cli@latest

确认安装是否,可以输入cobra-cli验证:

使用cobra-cli初始化go程序

cobra-cli init


初始化之后,可以看到自动创建了cmd文件夹,并增加了一些代码:

使用cobra-cli创建命令

如上,需要创建serve/log/db三个Command

cobra-cli add serve
cobra-cli add log
cobra-cli add db


此时可以看到cmd文件夹增加了三个文件:serve.go/log.go/db.go

定义接收参数的结构体

新建一个config文件夹,在config文件夹下新建一个config.go文件。文件内容如下:

package configvar Config AppConfigtype AppConfig struct {ServeConfig    ServeConfigLogConfig      LogConfigDataBaseConfig DataBaseConfig
}
type ServeConfig struct {IP   stringPort int
}
type LogConfig struct {Path  stringLevel string
}
type DataBaseConfig struct {Type           stringConnnectionStr string
}

在各命令中接收Flag的值

rootCmd/logCmd/dbCmd/serveCmd都是cobra.Command类型,这个类型有许多方法。举例说明其中几个最重要的方法:
Bool:func (f *FlagSet) Bool(name string, value bool, usage string) *bool
BoolVar:func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string)
BoolP:func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool
BoolVarP:func BoolVarP(p *bool, name, shorthand string, value bool, usage string)
其中:

  • 返回*bool的为BoolBoolP方法,使用返回值接收Flag的值
  • BoolVarBoolVarP传入Bool指针赋值到变量,区别是是否支持短名称(-)
    开始写代码:
    root.go:
/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>
*/
package cmdimport ("os""github.com/spf13/cobra"
)// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{Use:   "cobratest",Short: "a test for cobra",Long:  `a test for cobra`,// Uncomment the following line if your bare application// has an action associated with it:// Run: func(cmd *cobra.Command, args []string) { },
}// 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.
func Execute() {err := rootCmd.Execute()if err != nil {os.Exit(1)}
}

serve.go:

/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>
*/
package cmdimport ("cobratest/config""fmt""github.com/spf13/cobra"
)// serveCmd represents the serve command
var serveCmd = &cobra.Command{Use:   "serve",Short: "define the which ip and port to bind",Long:  `define the which ip and port to bind.`,Run: func(cmd *cobra.Command, args []string) {fmt.Println("serve called")fmt.Println(config.Config.ServeConfig)},
}func init() {rootCmd.AddCommand(serveCmd)//解析 serve --ip=xxx,不使用短名称serveCmd.Flags().StringVarP(&config.Config.ServeConfig.IP, "ip", "", "0.0.0.0", "--ip=your_ip")//解析 serve --port=xxx或者serve -p=xxxserveCmd.Flags().IntVarP(&config.Config.ServeConfig.Port, "port", "p", 10001, "--port=your_port or -p=your_port")
}

log.go:

/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>
*/
package cmdimport ("cobratest/config""fmt""github.com/spf13/cobra"
)// logCmd represents the log command
var logCmd = &cobra.Command{Use:   "log",Short: "define the app's log directory and app's log level",Long:  `define the app's log directory and app's log level.`,Run: func(cmd *cobra.Command, args []string) {fmt.Println("log called")fmt.Println(config.Config.LogConfig)},
}func init() {rootCmd.AddCommand(logCmd)// Here you will define your flags and configuration settings.// Cobra supports Persistent Flags which will work for this command// and all subcommands, e.g.:// logCmd.PersistentFlags().String("foo", "", "A help for foo")// Cobra supports local flags which will only run when this command// is called directly, e.g.:logCmd.Flags().StringVarP(&config.Config.LogConfig.Path,"directory", "d", "C:/log", "--directory=your_path or -d=your_path")logCmd.Flags().StringVarP(&config.Config.LogConfig.Level,"level","l","trace","-l=your_log_level or --level=your_log_level")
}

db.go:

/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>
*/
package cmdimport ("cobratest/config""fmt""github.com/spf13/cobra"
)// dbCmd represents the db command
var dbCmd = &cobra.Command{Use:   "db",Short: "define the db configurations",Long:  `define the db configurations.`,Run: func(cmd *cobra.Command, args []string) {fmt.Println("db called")fmt.Println(config.Config.DataBaseConfig)},
}func init() {rootCmd.AddCommand(dbCmd)// Here you will define your flags and configuration settings.// Cobra supports Persistent Flags which will work for this command// and all subcommands, e.g.:// dbCmd.PersistentFlags().String("foo", "", "A help for foo")// Cobra supports local flags which will only run when this command// is called directly, e.g.:dbCmd.Flags().StringVarP(&config.Config.DataBaseConfig.ConnnectionStr, "string", "s", "", "--string=your_connection_string or -s=your_connection_string")dbCmd.Flags().StringVarP(&config.Config.DataBaseConfig.Type, "type", "t", "mysql", "--type=your_type or -t=your_type")
}

运行测试

使用cobra创建的命令行工具,自带help命令和-h/--helpFlag
.\cobratest.exe -h

.\cobratest.exe -h
a test for cobraUsage:cobratest [command]Available Commands:completion  Generate the autocompletion script for the specified shelldb          define the db configurationshelp        Help about any commandlog         define the app's log directory and app's log levelserve       define the which ip and port to bindFlags:-h, --help   help for cobratestUse "cobratest [command] --help" for more information about a command.

serve命令:

.\cobratest.exe serve --ip 192.168.1.1 -p=1000
serve called
{192.168.1.1 1000}

db命令

.\cobratest.exe db -t=mysql -s=xxx
db called
{mysql xxx}

log命令

 .\cobratest.exe log -d=d:/log -l=error
log called
{d:/log error}


help命令和-h Flag

go cobra初试相关推荐

  1. Linux 查看进程的几个命令

    查看进程状态的基础指令,有以下几个常用参数: ps 查看当前终端下的命令 top 查看所有的进程(是动态的) 本文重点介绍通过ps命令查看进程 一:一些常用的参数组合及解析 1. 查看包含其他使用者的 ...

  2. 初试linux编译(ubuntu+vim)+玩转智能蛇

    一.初试linux编译(ubuntu+vim) 步骤: ①下载vmware15+ubuntu桌面版映像 ②安装ubuntu ③下载vim+gcc 在ubuntu终端输入: sudo apt-get i ...

  3. 北邮计算机科学技术是学硕吗,【计算机考研】2020北京邮电大学计算机科学与技术考研初试科目、参考书目、复试详情汇总...

    原标题:[计算机考研]2020北京邮电大学计算机科学与技术考研初试科目.参考书目.复试详情汇总 一.考试科目 计院的学硕是计算机科学与技术,专硕为计算机技术. 计算机科学与技术: ①101思想政治理论 ...

  4. 浙江大学计算机研究生分数线初试单科学科,2016年浙江大学计算机考研复试分数线_浙江大学考研分数线...

    成绩查询的时间越来越近了,来看看历年的分数线来估算一下自己是准备复试还是准备调剂吧,小编为大家整理了2016年浙江大学计算机考研复试分数线赶紧来看看.小编还为大家精心准备了浙江大学2016年计算机考研 ...

  5. 计算机复试被刷的3个经历,13年北大物理院光学考研初试第1名复试被刷经历_跨考网...

    先简单介绍一下自己,我本科毕业于一所普通211物理系,2013年报考北京大学物理学院光学专业,初试成绩为:英语61,政治70,量子力学107,电磁学与电动力学120,总分358,是光学专业初试第一名, ...

  6. 程序员初试和复试_程序员的软微mem经验贴

    一背景 程序员一枚,在刷朋友圈时候看到有朋友发招生简章,突然来了兴致,决定试一把. 本科16年毕业刚刚符合报名资格,对现在状态比较满意,不愿意摆脱社会人身份,所以报名了非全日制.的人工智能方向(毕竟是 ...

  7. BCH阵营对立将导致共识失败?Cobra有话说!

    近日,nchain首席科学家Craig Wright提出的bitcoin SV节点引发了BCH社区各方在其发展方向上激烈争论,无论是孰对孰错,理念之争终归是为了BCH的未来发展.这同时也正说明了BCH ...

  8. 比特币官网管理者Cobra认可BCH支付属性

    昨天,比特币官网 http://Bitcoin.org的管理者Cobra发推称:"仿佛回到了比特币的往日岁月,对比特币现金如此兴奋,几乎让我有了负罪感,但支付非常重要,而比特币现金在这一应用 ...

  9. 西农计算机考研专业课压分,考研:西农大计算机初试第一名被淘汰,倒数第一成功逆袭...

    近期看了多所高校的考研录取名单,发现一个很普遍的现象,如果该校最终要刷的人是个位数,那么一般倒数第一都能逆袭成功上岸,而被淘汰掉的考生之中很大概率有初试高分者,且淘汰的原因就是面试不合格.在昨日西农大 ...

最新文章

  1. 编辑流程图_作为一名采购商,做不好采购?送你5套采购流程图模板
  2. 创建electron应用
  3. 八十六、推荐组件的redux-thunk异步解决方案、Ajax获取推荐数据
  4. 完成一个H.265/HEVC码流分析工具
  5. linux上创建RAID(磁盘阵列)与LVM(逻辑盘)
  6. 深度学习(二十二)Dropout浅层理解与实现
  7. 项目模板参数化(上)
  8. 精灵图的使用(HTML、CSS)
  9. nginx发布静态目录备忘
  10. Linux系统怎么复制文件夹下的全部文件到另外文件夹?...
  11. Raid5数据恢复原理以及raid5数据恢复成功案例
  12. macosx安装之旅(8)-常见问题(转载)
  13. [转] 一些你不知道但是超美的地方,一定要去
  14. 24C02 EEPROM多个字节连续写入乱码问题解决
  15. 抓取网络源码python_python中的复仇者网络抓取实体提取和网络图
  16. 基于spring boot的毕业设计论文选题申报管理系统设计与实现 毕业论文+项目源码、
  17. 使用udp协议实现服务器端程序时,uIP中UDP协议实现的改进
  18. 友好城市(线性dp)
  19. eclipse中进行java编程时,CTRL+左键时,看不到源码的解决方法。
  20. UGA5TBYB_E_USG.exe

热门文章

  1. 小米电脑重装系统后亮度无法调节的解决办法
  2. linux复制操作 cp: -r not specified; omitting directory XXX 错误
  3. 计算机网络中的网络安全
  4. MySQL视图——创建视图、修改视图、删除视图、查看视图和更新视图
  5. 什么是阻抗匹配以及为什么要阻抗匹配
  6. 生物信息学笔记01-- 绪论
  7. 转载:Java语言学习
  8. Linux 字符集设置
  9. 《java与模式》中模式总结
  10. gamma原理及快速实现算法(C/C++)