package main import ( "flag" "fmt" ) func main() { flag.Parse() args := flag.Args() if len(args) <= 0 { fmt.Println("Usage: admin-cli [command]") return } switch args[0] { case "help": // ... case "export": //... if len(args) == 3 { // 匯出到檔案 // todo } else if len(args) == 2 { // 匯出... // todo } default: //... } }
package main import ( "fmt" "github.com/spf13/cobra" "os" ) // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "api", Short: "A brief description of your application", Long: `A longer description `, } // 命令一 var mockMsgCmd = &cobra.Command{ Use: "mockMsg", Short: "批次傳送測試文字訊息", Long: ``, Run: func(cmd *cobra.Command, args []string) { fmt.Println("mockMsg called") }, } // 命令二 var exportCmd = &cobra.Command{ Use: "export", Short: "匯出資料", Long: ``, Run: func(cmd *cobra.Command, args []string) { fmt.Println("export called") }, } func Execute() { err := rootCmd.Execute() if err != nil { os.Exit(1) } } func init() { rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") rootCmd.AddCommand(mockMsgCmd) rootCmd.AddCommand(exportCmd) exportCmd.Flags().StringP("out", "k", "./backup", "匯出路徑") } func main() { Execute() }
$ go run main.go A longer description Usage: api [command] Available Commands: completion Generate the autocompletion script for the specified shell export 匯出資料 help Help about any command mockMsg 批次傳送測試文字訊息 Flags: -h, --help help for api -t, --toggle Help message for toggle Use "api [command] --help" for more information about a command.
$ ./appName command args --Flag
$ go get -u github.com/spf13/cobra@latest
import "github.com/spf13/cobra"
# 命令列工具 $ go install github.com/spf13/cobra-cli@latest
$ cobra-cli --help 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. Usage: cobra-cli [command] Available Commands: add Add a command to a Cobra Application completion Generate the autocompletion script for the specified shell help Help about any command init Initialize a Cobra Application Flags: -a, --author string author name for copyright attribution (default "YOUR NAME") --config string config file (default is $HOME/.cobra.yaml) -h, --help help for cobra-cli -l, --license string name of license for the project --viper use Viper for configuration Use "cobra-cli [command] --help" for more information about a command.
$ cobra-cli init
├── LICENSE ├── cmd │ └── root.go └── main.go
package main import "tools/api/cmd" func main() { cmd.Execute() }
root.go(有刪減):
package cmd import ( "fmt" "github.com/spf13/cobra" ) // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "api", Short: "A brief description of your application", Long: `A longer description `, //Run: func(cmd *cobra.Command, args []string) { // fmt.Println("api called") //}, } // 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() { // 全域性flag // rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.api.yaml)") // local flag,暫不知道用處 rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }
$ go build $ ./api
A longer description Usage: api [command] Available Commands: completion Generate the autocompletion script for the specified shell help Help about any command Flags: -h, --help help for api -t, --toggle Help message for toggle Use "api [command] --help" for more information about a command.
$ cobra-cli add [command]
$ cobra-cli add mock-msg mockMsg created at /Users/xxx/repo/tools/api
package cmd import ( "fmt" "github.com/spf13/cobra" ) var mockMsgCmd = &cobra.Command{ Use: "mockMsg", Short: "A brief description of your command", Long: `mock msg command`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("mockMsg called") }, } func init() { rootCmd.AddCommand(mockMsgCmd) }
$ go build $ ./api
// ... Available Commands: completion Generate the autocompletion script for the specified shell help Help about any command mockMsg A brief description of your command // ...
$ ./api mockMsg mockMsg called
./api mockMsg help 批次生產mq訊息 Usage: benchmark mockmsg [flags] Flags: -g, --goroutine int32 並行routine數量 (default 1) -h, --help help for mockmsg -p, --packet int32 每個routine一秒寫入mq的數量 (default 20)
-g和-p是新增的2個flag:
func init() { mockmsgCmd.Flags().Int32P("goroutine", "g", 1, "並行routine數量") mockmsgCmd.Flags().Int32P("packet", "p", 20, "每個routine一秒寫入mq的數量") rootCmd.AddCommand(mockmsgCmd) }
// mockmsgCmd represents the mockmsg command var mockmsgCmd = &cobra.Command{ Use: "mockmsg", Short: "批次生產mq訊息", Run: func(cmd *cobra.Command, args []string) { // 這裡要寫全名 g, _ := cmd.Flags().GetInt32("goroutine") p, _ := cmd.Flags().GetInt32("packet") fmt.Println("mockmsg called,flags:g=", g, ",p=", p, ",args:", args) }, }
$ go run main.go mockmsg -p 322 -g 5 args1 args2 mockmsg called,flags:g= 5 ,p= 322 ,args: [args1 args2]