当前位置:网站首页>Getting started with the go Cobra command line tool

Getting started with the go Cobra command line tool

2022-06-24 23:00:00 Illusory private school

High quality resource sharing

Learning route guidance ( Click unlock ) Knowledge orientation Crowd positioning
🧡 Python Actual wechat ordering applet 🧡 Progressive class This course is python flask+ Perfect combination of wechat applet , From the deployment of Tencent to the launch of the project , Create a full stack ordering system .
Python Quantitative trading practice beginner Take you hand in hand to create an easy to expand 、 More secure 、 More efficient quantitative trading system

brief introduction

Github:https://github.com/spf13/cobra
Star:26.5K
 
Cobra It's a use. Go Language implementation of command line tools . And now it is used by many projects , for example :Kubernetes、Hugo and Github CLI etc. . By using Cobra, We can quickly create command line tools , Especially suitable for writing test scripts , All kinds of services Admin CLI etc. .
 
such as Mattermost project , I wrote a lot Admin CLI:

Why cobra

Let's look at a simple demo

Before using

?

| 123456789101112131415161718192021222324252627282930 | packagemain import(``"flag"``"fmt"``) funcmain() {``flag.Parse() args := flag.Args()``iflen(args) <= 0 {``fmt.Println(``"Usage:  admin-cli [command]"``)``return``} switchargs[0] {``case"help"``:``// ...``case"export"``:``//...``iflen(args) == 3 { // Export to file ``// todo``}elseiflen(args) == 2 { // export ...``// todo``}``default``:``//...``}``} |

After using

?

| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 | packagemain import(``"fmt"``"github.com/spf13/cobra"``"os"``) // rootCmd represents the base command when called without any subcommands``varrootCmd = &cobra.Command{``Use:"api"``,``Short:"A brief description of your application"``,``Long:  A longer description ,``} // Command one ``varmockMsgCmd = &cobra.Command{``Use:"mockMsg"``,``Short:" Send test text messages in batches "``,``Long:  ``,``Run:func``(cmd *cobra.Command, args []string) {``fmt.Println(``"mockMsg called"``)``},``} // Command two ``varexportCmd = &cobra.Command{``Use:"export"``,``Short:" Derived data "``,``Long:  ``,``Run:func``(cmd *cobra.Command, args []string) {``fmt.Println(``"export called"``)``},``} funcExecute() {``err := rootCmd.Execute()``iferr != nil {``os.Exit(1)``}``} funcinit() {``rootCmd.Flags().BoolP(``"toggle"``,"t"``, false,"Help message for toggle"``) rootCmd.AddCommand(mockMsgCmd)``rootCmd.AddCommand(exportCmd) exportCmd.Flags().StringP(``"out"``,"k"``,"./backup"``," export path "``)``} funcmain() {``Execute()``} |

function :

?

| 1234567891011121314151617 | $ go run main.go``A longer description Usage:``api [``command``] Available Commands:``completion  Generate the autocompletion scriptforthe specified shell``export      Derived data ``help        Help about anycommand``mockMsg     Send test text messages in batches  Flags:``-h, --help     helpforapi``-t, --toggle   Help messagefortoggle Use"api [command] --help"formoreinformation about acommand``. |

Have you found it? ? You don't have to deal with parameter combinations anymore , From then on, he was released , Just write your own business logic !

Basic concepts

Cobra It's made up of three parts :

  • command (Commands ): Represent behavior . Commands are the central point of the program , Every function of the program should be able to interact through commands , A command can have any subcommand .
  • Parameters (Args): Arguments to the command
  • sign (Flags): Decorating commands . It embellishes how the command should be done .

The official recommended command format is :

?

| 1 | $ .``/appNamecommandargs --Flag |

Such as hugo server --port=1313 :

  • appName: hugo
  • command: server
  • flag: port

install

Go pkg

Add dependency

?

| 1 | $ go get -u github.com``/spf13/cobra``@latest |

Just import :

?

| 1 | import"github.com/spf13/cobra" |

Command line tools

It is recommended to install the command line tool cobra-cli , To facilitate the quick creation of cobra project , increase command etc. .

?

| 12 | # Command line tools ``$ goinstallgithub.com``/spf13/cobra-cli``@latest |

After installation , perform cobra-cli --help ( Please make sure GOBIN The configured ), Output the following information to indicate success :

?

| 1234567891011121314151617181920212223 | $ cobra-cli --help``Cobra is a CLI libraryforGo 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 acommandto a Cobra Application``completion  Generate the autocompletion scriptforthe specified shell``help        Help about anycommand``init        Initialize a Cobra Application Flags:``-a, --author string    author nameforcopyright attribution (default"YOUR NAME"``)``--config string    configfile(default is $HOME/.cobra.yaml)``-h, --help             helpforcobra-cli``-l, --license string   name of licenseforthe project``--viper            use Viperforconfiguration Use"cobra-cli [command] --help"formoreinformation about acommand``. |

An introduction to the practice

newly build cobra Command line program

Installed cobra-cli After the tool , perform init Initialize create project :

?

| 1 | $ cobra-cli init |

here , The following files are automatically generated in the current directory :

?

| 1234 | ├── LICENSE``├── cmd``│   └── root.go``└── main.go |

main.go:

?

| 1234567 | packagemain import"tools/api/cmd" funcmain() {``cmd.Execute()``} |

?

| 1 | root.``go``( With deletion ): |

?

| 12345678910111213141516171819202122232425262728293031323334 | packagecmd import(``"fmt" "github.com/spf13/cobra"``) // rootCmd represents the base command when called without any subcommands``varrootCmd = &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.``funcExecute() {``err := rootCmd.Execute()``iferr != nil {``os.Exit(1)``}``} funcinit() {``// overall situation flag``// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.api.yaml)") // local flag, I don't know the use for the time being ``rootCmd.Flags().BoolP(``"toggle"``,"t"``, false,"Help message for toggle"``)``} |

At this time to run , Do not specify parameters , Will execute rootCmd, Print instructions :

?

| 12 | $ go build$ .``/api |

Output :

?

| 1234567891011121314 | A longer description Usage:``api [``command``] Available Commands:``completion  Generate the autocompletion scriptforthe specified shell``help        Help about anycommand Flags:``-h, --help     helpforapi``-t, --toggle   Help messagefortoggle Use"api [command] --help"formoreinformation about acommand``. |

Orders constitute

Analyze the default output above :

  • Available Commands: Represents an executable command . such as ./api connect
  • Flags: Is the parameter . such as ./api connect --ip=127.0.0.1:6379,–ip Namely flag,127.0.0.1:6379 Namely flag Value .

The new command

Let's try a new command , This is also the charm of command-line programs , Perform different actions with different parameters .
grammar :

?

| 1 | $ cobra-cli add [``command``] |

such as :

?

| 12 | $ cobra-cli add mock-msg``mockMsg created at/Users/xxx/repo/tools/api |

here , stay cmd There will be one more file next (mock_msg.go), The contents are as follows :

?

| 1234567891011121314151617181920 | packagecmd import(``"fmt" "github.com/spf13/cobra"``) varmockMsgCmd = &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"``)``},``} funcinit() {``rootCmd.AddCommand(mockMsgCmd)``} |

Re execution rootCmd:

?

| 12 | $ go build``$ .``/api |

Will find , One more command :

?

| 123456 | //...``Available Commands:``completion  Generate the autocompletion scriptforthe specified shell``help        Help about anycommand``mockMsg     A brief description of yourcommand``//... |

perform mocMsg command :

?

| 123 | $ .``/apimockMsg mockMsg called |

here , Can be generated in  mock_msg.go: Run() Function , Put your own business logic code .

How to display your own command usage

A new command has been added mockMsg, adopt ./api help Printed commands and help, however Use Where are the specified contents printed ?
 
This is the time , Need to aim at Command In the specified help, At this point, you can print the specific usage of this command .

?

| 12345678910 | .``/apimockMsg help`` Volume production mq news  Usage:``benchmark mockmsg [flags] Flags:``-g, --goroutine int32   Concurrent routine Number (default 1)``-h, --help              helpformockmsg``-p, --packet int32      Every routine Write in one second mq The number of (default 20) |

?

| 1 | -g and -p It's new 2 individual flag: |

?

| 123456 | funcinit() {``mockmsgCmd.Flags().Int32P(``"goroutine"``,"g"``, 1," Concurrent routine Number "``)``mockmsgCmd.Flags().Int32P(``"packet"``,"p"``, 20," Every routine Write in one second mq The number of "``) rootCmd.AddCommand(mockmsgCmd)``} |

Get this 2 It's worth :

?

| 1234567891011 | // mockmsgCmd represents the mockmsg command``varmockmsgCmd = &cobra.Command{``Use:"mockmsg"``,``Short:" Volume production mq news "``,``Run:func``(cmd *cobra.Command, args []string) {``// Write your full name here ``g, _ := cmd.Flags().GetInt32(``"goroutine"``)``p, _ := cmd.Flags().GetInt32(``"packet"``)``fmt.Println(``"mockmsg called,flags:g="``, g,",p="``, p,",args:"``, args)``},``} |

perform :

?

| 12 | $ go run main.go mockmsg -p 322 -g 5 args1 args2``mockmsg called,flags:g= 5 ,p= 322 ,args: [args1 args2] |

summary

Let's take an example , Introduced the use of cobra Benefits . Through a complete introductory practice , Demonstrates creating a project 、 Add some examples of commands and usage , I hope it helped you !
 
Reference resources :

原网站

版权声明
本文为[Illusory private school]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241705498156.html