golang cli 构建工具-cobra

官网
    https://cobra.dev/ A Framework for Modern CLI Apps in Go

安装cobra

go install github.com/spf13/cobra-cli@latest

    将cobra下载完成后,GOPATH/bin目录会生成一个cobra可执行程序,通过这个程序我们可以初始化一个cobra代码框架。

初始化一个demo工程

mkdir cobratest  &&  cd cobratest
go mod init cobratest
cobra-cli init

cobra-cli

cobra-cli add test // 添加子命令test,自动生成 cmd/test.go

完整示范

  var name string
  var age int

  // rootCmd represents the base command when called without any subcommands
  var rootCmd = &cobra.Command{
    Use:   "cobratest",
    Short: "A brief description of your application",
    Long: `A longer description that spans multiple lines and likely contains`,
    Run: func(cmd *cobra.Command, args []string) { // run方法为命令的运行执行方法
      fmt.Println("cobratest", args, name, age)
    },
  }

  func Execute() { // 执行入口 见 main.go cmd.Exceute()
    err := rootCmd.Execute()
    if err != nil {
      os.Exit(1)
    }
    rootCmd.AddCommand(testCmd) // 添加一个子命令
  }

  func initConfig() {
  }

  func init() {
    cobra.OnInitialize(initConfig)
    rootCmd.Flags().StringVarP(&name, "name", "n", "", "person's name")
    rootCmd.Flags().IntVarP(&age, "age", "a", 0, "person's age")
  }

  var testCmd = &cobra.Command{ // 子命令test定义
    Use:   "test",
    Short: "A brief description of your command",
    Long: `A longer description that spans multiple lines and likely contains examples`,
    Run: func(cmd *cobra.Command, args []string) {
      fmt.Println("test called")
    },
  }

go run main.go -a 12 -n ww => cobratest [] ww 12 // 主命令
go run main.go test => test called // 子命令test

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值