1. Cobra库介绍
2. 库学习
2.1 源码库例子解析
package main
import (
"fmt"
"strings"
"github.com/spf13/cobra"
)
func main() {
var echoTimes int
var cmdPrint = &cobra.Command{
Use: "print [string to print]",
Short: "Print anything to the screen",
Long: `print is for printing anything back to the screen.
For many years people have printed back to the screen.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Print: " + strings.Join(args, " "))
},
}
var cmdEcho = &cobra.Command{
Use: "echo [string to echo]",
Short: "Echo anything to the screen",
Long: `echo is for echoing anything back.
Echo works a lot like print, except it has a child command.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Echo: " + strings.Join(args, " "))
},
}
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, " "))
}
},
}
cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
var rootCmd = &cobra.Command{Use: "app"}
rootCmd.AddCommand(cmdPrint, cmdEcho)
cmdEcho.AddCommand(cmdTimes)
rootCmd.Execute()
}
- Args:可以对于参数进行相关的校验,提供的校验方式有
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 an 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.
- 一个层级可以加多个方法,一个方法上可以在追加嵌套一个方法
- rootCmd.AddCommand(func1,func2...): 一个层级追加多个方法
- func1.AddCommand(subFunc1, subFunc2...):在追加嵌套一个方法
- 参数解析方式
- cmdTimes.Flags().类型:只有当前的命令可以使用该参数
- cmdTimes. PersistentFlags().类型:当前命令以及该命令的子命令都需要支持;
- rootCmd.MarkFlagRequired("region"):对于如果没有设置region参数的命令就会有问题
- 添加Hook
- PreRun:真正的Run开始执行前先操作的步骤
- PostRun:真正的Run执行后的操作