cobra几乎是每个学习golang的码农必备的技能,简要来说,他是个编写命令行的工具,在大型项目中经常使用cobra来启动服务,接下来直接上代码

root.go

package cmdimport ("fmt""os""github.com/spf13/cobra""github.com/spf13/viper"
)var Verbose bool
var Author string
var Author2 string
var Author3 string
var Test boolvar rootCmd = &cobra.Command{Use:   "hugo",Short: "Hugo is a very fast static site generator",Args:  cobra.NoArgs,// NoArgs - the command will report an error if there are any positional args.// ArbitraryArgs - the command will accept any args.// OnlyValidArgs - the command will report an error if there are any positional args that are not in the ValidArgs field of Command.// MinimumNArgs(int) - the command will report an error if there are not at least N positional args.// MaximumNArgs(int) - the command will report an error if there are more than N positional args.// ExactArgs(int) - the command will report an error if there are not exactly N positional args.// ExactValidArgs(int) = the command will report and error if there are not exactly N positional args OR if there are any positional args that are not in the ValidArgs field of Command// RangeArgs(min, max) - the command will report an error if the number of args is not between the minimum and maximum number of expected args.// Args match a function ,so you can difine your own functionLong: `A Fast and Flexible Static Site Generator built withlove by spf13 and friends in Go.Complete documentation is available at http://hugo.spf13.com`,Run: func(cmd *cobra.Command, args []string) {fmt.Println("main root")fmt.Println(cmd.Flags().GetString("author"))fmt.Println(viper.Get("author"))fmt.Println(cmd.Flags().GetBool("test"))// Do Stuff Here},// PersistentPreRun// PreRun// Run// PostRun// PersistentPostRun/**以上key按顺序执行对应的函数,而Persistent代表始终执行,并且对于子命令也一样,如果子命令没有定义Persistent的key的话,则执行父命令的Persistent*Run函数。**/}func Execute() {if err := rootCmd.Execute(); err != nil {fmt.Println(err)os.Exit(1)}
}func init() {cobra.OnInitialize(initConfig) //这会在运行每个子命令之前运行,后面无法更新viper中初始config的数据rootCmd.PersistentFlags().StringVarP(&Author, "author", "a", "defaultAuthor", "作者名")rootCmd.PersistentFlags().StringVar(&Author2, "author2", "defaultAuthor2", "作者名2")rootCmd.PersistentFlags().String("author3", "defaultAuthor3", "作者名3")/**方法名带P的则代表可在参数中添加短声明,带有Var的则代表可以将值绑定到变量中**/viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))// 将用户输入的author信息绑定到viper缓存中,优先级低于viper本身从配置信息中读取的绑定rootCmd.Flags().BoolVarP(&Test, "test", "t", false, "test")// PersistentFlags为全局Flag,不带Persistent的为本地Flagviper.BindPFlag("author", rootCmd.Flags().Lookup("test"))// 绑定局部FlagrootCmd.MarkPersistentFlagRequired("author")rootCmd.MarkFlagRequired("author2")rootCmd.MarkPersistentFlagRequired("author3") // 仅对于全局Flag生效,标记其为必须输入的FlagrootCmd.MarkFlagRequired("test") // 仅对于局部Flag生效,标记其为必须输入的Flag
}func initConfig() {viper.AddConfigPath("./")viper.AddConfigPath("./conf")viper.SetConfigName("config")viper.SetConfigType("yaml")viper.AutomaticEnv()if err := viper.ReadInConfig(); err != nil {fmt.Println("Error:", err)os.Exit(1)}
}

version.go

package cmdimport ("fmt""github.com/spf13/cobra"
)var versionCmd = &cobra.Command{Use:              "version",Short:            "Print the version number of Hugo",TraverseChildren: true,// 用途不明Long: `All software has versions. This is Hugo's`,Args: cobra.MaximumNArgs(5),Run: func(cmd *cobra.Command, args []string) {fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")fmt.Println(cmd.Flags().GetString("name"))fmt.Println(cmd.Flags().GetString("author"))fmt.Println(args)},
}func init() {rootCmd.AddCommand(versionCmd)var Source stringversionCmd.Flags().StringVarP(&Source, "source", "s", "", "读取文件路径")var Name stringversionCmd.Flags().StringVarP(&Name, "name", "n", "default name", "你的名字")// rootCmd.SetArgs([]string{"version", "second-arg", "third-arg"})/**此命令可以设置全局初始参数,大概用于测试?例如此参数设置后可以直接进入version的子命令并添加两个参数**/
}

最后在main.go中执行root.go的Execute函数即可,注意init函数将会在程序执行之前执行来进行初始化,具体请参考另一篇博客关于init函数的介绍,关于viper的使用请参考viper的使用介绍

golang cobra简要使用介绍相关推荐

  1. golang cobra powershell补全脚本

    golang cobra powershell补全脚本 cobra 对于windows我个人觉得支持不是很好,所以写了下面的脚本,无论你怎么修改cobra都可以自适应补全命令. 原理就是使用cobra ...

  2. pcs和serdes_对Lattice ECP3/ECP5器件中的SerDes/PCS进行了简要的介绍

    FPGA发展到今天,SerDes (Serializer - Deserializer) 基本上是标配了.从PCI到PCI Express,从ATA到SATA,从并行ADC接口到JESD204,从RI ...

  3. Golang的开发工具介绍

    文章目录 前言 1. VScode +Go 插件 2. Goland 3. VIM 4. Eclipse IDE工具 5. LiteIDE 6. Emacs 7. Go Callvis 使用建议 前言 ...

  4. Golang之Channel详细介绍

    一.概述 通道(Channel)是 Golang 在语言级别上提供的 goroutine 间的通讯方式,可以使用channel在多个 goroutine 之间传递消息.如果说 goroutine 是 ...

  5. golang(07) 结构体介绍

    原文链接 http://www.limerence2017.com/2019/09/11/golang12/ golang支持面向对象的设计,一般支持面向对象的语言都会有class的设计,但是gola ...

  6. 用纯JS做俄罗斯方块 - 简要思路介绍(1)

    大家都知道俄罗斯方块是一款大众化的游戏了,我很小的时候就玩过,今年已经25岁了,可以说俄罗斯方块确实是历史悠久,做俄罗斯方块是我上个星期开始的想法.也许是由于自己从来没有写过这种东西吧,所以有生疏.代 ...

  7. Scikit-learn学习系列 | 1. sklearn的简要使用介绍与数据集获取

    如有错误,恳请指出. 以下内容整理自专栏:博主"文火冰糖的硅基工坊"的专栏--机器学习与scikit-learn,对部分的文章的简化与整理. 文章目录 1. scikit-lear ...

  8. Golang filepath包常用方法介绍

    本文介绍与文件路径相关包,该工具包位于path/filepath中,该包试图与目标操作系统定义的文件路径兼容.本文介绍一些常用函数,如获取文件绝对路径,获取文件名或目录名.遍历文件.分割文件路径.文件 ...

  9. golang菜鸟的自我介绍

    大家好,今天我从一个看csdn博客的读者.变成一个创作者.我是一名专科生.学的是计算机网络,因为网络安全等机缘巧合接触到了docker.了解到了golang.对编程0基础的我.选择了拥护golang, ...

最新文章

  1. python3 判断ip类型 ipv4 ipv6
  2. 正文处理命令及tar命令
  3. IDEA 方法注释模板和类注释模板
  4. Java NIO3:缓冲区Buffer
  5. springboot幂等性_如何使用 SpringBoot + Redis 优雅的解决接口幂等性问题
  6. 产品经理被首杀一万次的真相?CTO怼天怼地的原因?市场妹子缘何咆哮?欢迎走近这局互联网狼人杀~...
  7. Vue 第一天学习 ---2018.06.28
  8. OpenCASCADE:使用扩展数据交换 XDE之读写 STEP 或 IGES
  9. 使用idea编写SparkStreaming消费kafka中的数据,并对数据进行某一指标的处理【小案例】(五)
  10. Notepad++的安装和基本使用
  11. vim编辑器初级(七)
  12. 你见过哪些操蛋的代码?
  13. [Fanly Submit V4.1]WordPress插件普通收录
  14. 在Centos环境下搭建Confluence
  15. python实现多进程监听声音播放并绘图
  16. Ubuntu下网络调试助手 NetAssist
  17. 用单片机c语言输入8位输出,单片机C语言教程(二)
  18. 3500常用字+字母+数字+表单符号
  19. 《C++ Primer 5th》知识点总结练习题解
  20. 经营计划与经营利润分析动态报表的实现--业务需求

热门文章

  1. 云杉网络:SDN让企业在云端实现无缝拓展
  2. 男生学会计专业好还是学计算机专业,计算机和会计哪个难学 哪个更有发展前景...
  3. shiro中devtools:java.lang.ClassCastException: cn.model.User cannot be cast to cn.model.User
  4. 高效清洗即洗即穿!买洗烘一体洗衣机注意这几点
  5. 忻州师范学院计算机系的系云,忻州师范学院教务管理系统入口http://jwc.xztu.edu.cn/...
  6. k8s平台搭建,dashboard图形化管理,纯实例
  7. Apache httpd.conf配置文件AllowOverride参数详解
  8. oracle tuexdo,Tuxedo入门
  9. folly 之 fbstring
  10. 卷积后的特征有负数吗?_赠书 | 人工智能识万物:卷积神经网络的前世今生