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

你可能感兴趣的:(golang,golang,开发语言,后端)