go命令行工具,cobra-cli使用教程

1,526 阅读2分钟

1.先安装依赖

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

2.创建文件夹cobor,在文件夹里面执行

go mod init cobra

3.项目初始化,执行命令

cobra-cli init

image.png

4.增加一个购买电影票的命令

/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>

*/
package cmd

import (
   "fmt"
   "os"

   "github.com/spf13/cobra"
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
   Use:   "cobra",
   Short: "A brief description of your application",
   Long: `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.`,
   // Uncomment the following line if your bare application
   // has an action associated with it:
   // Run: func(cmd *cobra.Command, args []string) { },
}

var (
   count    int
   time     string
   location string
)

var bugTicket = &cobra.Command{
   Use:   "购买火车票",
   Short: "",
   Long:  "",
   Run: func(cmd *cobra.Command, args []string) {
      fmt.Println("count", count)
      i := len(args)
      if i == 0 {
         fmt.Println("没有输入火车票名字")
      } else if i == 1 {
         fmt.Println("购买火车票 %s %s %s %s 张 ", location, time, args[0], count)
      } else if i > 0 {
         fmt.Println("不能一次购买多张")
      }
   }}

// 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.
func Execute() {
   err := rootCmd.Execute()
   if err != nil {
      os.Exit(1)
   }
}

func init() {
   rootCmd.AddCommand(bugTicket)
   bugTicket.Flags().IntVar(&count, "数量", 1, "购票张数")
   bugTicket.MarkFlagRequired("数量")

   bugTicket.Flags().StringVar(&time, "时间", "", "购买时间")
   bugTicket.MarkFlagRequired("时间") //

   bugTicket.Flags().StringVar(&time, "影院", "", "购买影院")
   bugTicket.MarkFlagRequired("影院") //// Here you will define your flags and configuration settings.
   // Cobra supports persistent flags, which, if defined here,
   // will be global for your application.

   // rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")

   // Cobra also supports local flags, which will only run
   // when this action is called directly.
   rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

使用go build main.go打包一个exe文件,

执行 命令 .\main.exe --数量=1 --时间=晚上7点 --影院=万达

ADDGroup命令教程

package main

import ( "fmt" "os"

"github.com/spf13/cobra"

)

var rootCmd = &cobra.Command{ Use: "myapp", Short: "A brief description of your application", Long: `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.`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("Welcome to my app!") }, }

var helloCmd = &cobra.Command{ Use: "hello", Short: "Say hello to someone", Long: This command allows you to greet someone by name., Run: func(cmd *cobra.Command, args []string) { name, _ := cmd.Flags().GetString("name") fmt.Printf("Hello, %s!\n", name) }, }

var byeCmd = &cobra.Command{ Use: "bye", Short: "Say goodbye to someone", Long: This command allows you to say goodbye to someone by name., Run: func(cmd *cobra.Command, args []string) { name, _ := cmd.Flags().GetString("name") fmt.Printf("Goodbye, %s!\n", name) }, }

func init() { helloCmd.Flags().StringP("name", "n", "", "The name of the person to greet") helloCmd.MarkFlagRequired("name")

byeCmd.Flags().StringP("name", "n", "", "The name of the person to say goodbye to")
byeCmd.MarkFlagRequired("name")

rootCmd.AddCommand(helloCmd)
rootCmd.AddCommand(byeCmd)

demoCmd := &cobra.Command{
	Use:   "demo",
	Short: "A demo command group",
	Long:  "This is a demo command group with subcommands.",
}
demoCmd.AddCommand(helloCmd, byeCmd)
rootCmd.AddCommand(demoCmd)

}

func main() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } }