首页 > 技术文章 > Go+Cobra快速入门

binHome 2020-11-14 13:24 原文

Cobra介绍

  • 一个用于生成命令行工具的框架(本身也是个命令行工具)
  • 非常简单,易用
  • k8s/docker/hugo/etcd等...

下载安装

https://github.com/spf13/cobra

$ go get -u github.com/spf13/cobra
// github.com/spf13/cobra/cobra/main.go 编译后可以放到 GOPTH/bin/ 就可以直接使用了
// 在程序项目中引用 import "github.com/spf13/cobra" 

初始化项目

/*
Usage:
  cobra init [name] [flags]

Aliases:
  init, initialize, initialise, create

Flags:
  -h, --help              help for init
      --pkg-name string   fully qualified pkg name

Global Flags:
  -a, --author string    author name for copyright attribution (default "YOUR NAME")
      --config string    config file (default is $HOME/.cobra.yaml)
  -l, --license string   name of license for the project
      --viper            use Viper for configuration (default true)
*/

// cobra 是github.com/spf13/cobra/cobra/main.go 编译后的可执行文件
// 基本初始化
cobra init --pkg-name xxx

// 修改作者信息
cobra init --pkg-name xxx --author xxx2

// 指定license信息
cobra init --pkg-name xxx -license xxx

命令的基本结构

var rootCmd = &cobra.Command{
	Use:   "clid", 
	Short: "A brief description of your application",
	Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	// Uncomment the following line if your bare application
	// has an action associated with it:
	//	Run: func(cmd *cobra.Command, args []string) { },
        //      Alias:[]string,
}
func init() {
	rootCmd.AddCommand(versionCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// versionCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// versionCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

// Use: 与短简介对应显示 在启动时显示
// Short: 简介,在命令行后会跟一个短的备注
// Long: 一个长的帮助信息,会在执行-h帮助的时候显示
// run: func(cmd *cobra.Command, args []string)  cmd是获取创建的对象指针可以获取信息比如选项 cmd.Flags().Get数据类型("参数名称"),args 获取没有捕获的参数并以切片返回 与 os.Args类似 ->执行对应use命令会执行对应的run函数  
// 在 init 函数中 rootCmd.AddCommand(versionCmd) rootCmd可以替换其他子命令生成的 cobra.Command 对象 实现嵌套关系

编译与运行

与Go程序编译运行一致,无特殊需求

为命令添加一个子命令

cobra add xxx // xxx是子命令
// 创建完成后会在cmd目录下生成一个xxx.go的文件

为命令添加一个选项

func init() {
	rootCmd.AddCommand(versionCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// versionCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
        // 添加参数
        // versionCmd.Flags().数据类型P("参数名称","短的名称",默认值,"提示信息")
        // 参数名称一般是 --参数名称
        // 短的选项一般是 -短的名称
        // 已经添加的参数在 run 函数中
	versionCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

选项的接受和处理

// versionCmd represents the version command
var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "A brief description of your command",
	Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("version called")
		// 获取参数
		v, err := cmd.Flags().GetString("toggle")
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println("v", v)
	},
}

修改默认选项

// 如果需要修改初始化的help选项  cobra/command.go
// 1.全部更改
// func (c *Command) InitDefaultHelpCmd()
// 2.部分修改
// func (c *Command) SetHelpFunc(f func(*Command, []string))/(c *Command) SetHelpCommand(cmd *Command)/(c *Command) SetHelpTemplate(s string)

推荐阅读