// rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "api", Short: "A brief description of your application", Long: `A longer description `, }
在这一点上,你可以运行 go run main.go ,它将运行你的应用程序。go run main.go serve、go run main.go config、go run main.go config create 以及 go run main.go help serve 等都可以工作。当然,如果你用的是 go build 命令来运行程序,那么 ./moduleName serve、./moduleName create 以及 ./moduleName serve 等都可以工作( moduleName 是当前文件的模块名)。
author: Steve Francia <spf@spf13.com> year: 2020 license: header: This file is part of CLI application foo. text: | {{ .copyright }}
This is my license. There are many like it, but this one is mine. My license is my best friend. It is my life. I must master it as I must master my life.
在上面的自定义许可证配置中,许可证文本中的 copyright 行是由 author 和 year 属性生成的。LICENSE 文件的内容是:
This is my license. There are many like it, but this one is mine. My license is my best friend. It is my life. I must master it as I must master my life.
// rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "test", 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() if err != nil { os.Exit(1) } }
// local flag rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }
如果此刻运行程序,不指定参数,会默执行 rootCmd ,打印使用说明
1 2 3 4 5 6
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.
var mockMsgCmd = &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
1 2
go build ./test
会发现多了一个命令,且多了 Flags 提示
1 2 3 4 5 6 7 8 9 10
... Available Commands: completion Generate the autocompletion script for the specified shell help Help about any command mockMsg A brief description of your command
Flags: -h, --help help for test -t, --toggle Help message for toggle ...
执行 mockMsg 命令:
1 2
./test mockMsg mockMsg called
可以发现程序输出了 mockMsg called ,这意味着它正常运行了,此时就可以在生成的 mockMsg.go: Run() 函数中,放你自己的业务代码了。
如何显示自己的命令用法
上面新增了一个命令 mockMsg ,通过 ./test -h 打印了命令的 help 内容,但是 Use 里面指定的内容打印到哪里去了呢?
这个时候,需要针对 Command 再指定 help,此时就能打印这个命令的具体用法了。(./test -h打印的是 rootCmd 的 help 内容,./test mockMsg -h 打印的是 mockMsg 内的 help 内容,两个 command 是父子关系)
var echoTimes int var cmdTimes = &cobra.Command{ Use: "times [string to echo]", Short: "Echo anything to the screen more times", Long: `echo things multiple times back to the user by providing a count and a string.`, Run: func(cmd *cobra.Command, args []string) { for i := 0; i < echoTimes; i++ { fmt.Println("Echo: " + strings.Join(args, " ")) } }, }
funcinit() { // 需要注意的是此处的 shorthand 只能为单个英文字符(包含大小写) // func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string fatherCmd.Flags().Int32P("source", "S", 8, "Int32 directory to read from") cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") // 给 father 子命令添加一个 cmdTimes 子命令 fatherCmd.AddCommand(cmdTimes) rootCmd.AddCommand(fatherCmd) }
// fatherCmd represents the father command var fatherCmd = &cobra.Command{ Use: "father", Short: "I'm son's father", Long: `This is a parent-child command relationship demo.`, Run: func(cmd *cobra.Command, args []string) { fmt.Print("father start\n\n") // 此处左侧的变量名必须和 shorthand 或者 name 保持一致 // GetXXX() 内要写全名 source, _ := cmd.Flags().GetInt32("source") fmt.Print("father called,flags:S=", source, ",args:", args, "\n\n") fmt.Println("son start") }, }
var echoTimes int var cmdTimes = &cobra.Command{ Use: "times [string to echo]", Short: "Echo anything to the screen more times", Long: `echo things multiple times back to the user by providing a count and a string.`, Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { for i := 0; i < echoTimes; i++ { fmt.Println("Echo: " + strings.Join(args, " ")) } }, }
funcinit() { // 需要注意的是此处的 shorthand 只能为单个英文字符(包含大小写) // func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string fatherCmd.Flags().Int32P("source", "S", 8, "Int32 directory to read from") cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") // 给 father 子命令添加一个 cmdTimes 子命令 fatherCmd.AddCommand(cmdTimes) rootCmd.AddCommand(fatherCmd) }
让我们再次试着编译运行程序,并使用 times 命令
1 2
go build ./test father times -t 10
返回结果:
1 2 3 4 5 6 7
Error: requires at least 1 arg(s), only received 0 Usage: test father times [string to echo] [flags]
Flags: -h, --help help for times -t, --times int times to echo the input (default 1)