golang命令行库cobra使用

github地址:https://github.com/spf13/cobra

Cobra功能

简单子命令cli 如  kubectl verion    kubectl get

自动识别-h,--help 帮助
更过参考官方手册:https://github.com/spf13/cobra

kubectl get pod --all-namespaces    get代表命令(command) pod代表事务(args)  --all-namespaces代表标识(flag),command代表动作,Args代表事务,flags代表动作的修饰符。

使用Cobra

使用cobra需要main.go或和cmd/cmd.go(非固定,根据官方手册说明操作的),来创建需要添加的命令。

cobra不需要构造函数,只需要创建命令即可

rootCmd = &cobra.Command{
    Use:   "db ",
    Short: "test1",
    Long:  `this is a test123`,
    Run: func(cmd *cobra.Command, args []string) {
	log.Println(cfgFile, port)
    },
}

func Execute() {
    if err := rootCmd.Execute(); err != nil {
        log.Fatal(err)
        os.Exit(1)
    }
}

还需要在init()方法中定义flag和handle等配置。

func init() {
    rootCmd.PersistentFlags().StringVar(&cfgFile, "c", "", "config file (default /etc/php.ini)")
    rootCmd.PersistentFlags().IntVar(&port, "p", 3306, "config file (default /etc/php.ini)")
}

创建main.go,在其初始化cobra

package main

import "your_app/cmd"

func main() {
    cmd.Execute()
}

使用flag

标志是args来控制动作command的操作方式的。

Persistent Flags:全局性flag 可用于它所分配的命令以及该命令下的每个命令。在根上分配标志作为全局flag。

Local Flags:局部性flag 在本args分配一个标志,该标志仅适用于该特定命令

Required flags:必选flag,flag默认是可选的。如果希望命令在未设置flag时报告错误,请将其标记为required

rootCmd.Flags().StringVarP(&cfgFile, "config", "c", "", "config file (require)")
rootCmd.MarkFlagRequired("config")

使用子命令

testCmd = &cobra.Command{
  Use:   "zhangsan",
  Short: "child command",
  Long:  `this is a child command`,
  Run: func(cmd *cobra.Command, args []string) {
  	fmt.Println("root > zhangsan")
  },
}

rootCmd.AddCommand(testCmd)

猜你喜欢

转载自www.cnblogs.com/LC161616/p/10487177.html