当前位置:网站首页>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 :
边栏推荐
- [WSL] SSH Remote Connection and host port forwarding configuration
- China solar thermal market trend report, technical dynamic innovation and market forecast
- 【Mongodb】READ_ ME_ TO_ RECOVER_ YOUR_ Data, the database is deleted maliciously
- Learning bit segment (1)
- China smallpox vaccine market trend report, technical innovation and market forecast
- 「ARM 架构」是一种怎样的处理器架构?
- Beijiafu (p+f) R2000 modified radar IP
- How to submit the shopee opening and settlement flow?
- Basic principles of layer 2 switching
- Research and investment strategy report on China's bridge anticorrosive coating industry (2022 Edition)
猜你喜欢

2022-06-10 work record --js- obtain the date n days after a certain date

Talk about GC mechanism often asked in interview

Cases of addition, deletion, modification and search of C # learning for two years and C # import and export (de duplication)

大厂面试必问:如何解决TCP可靠传输问题?8张图带你详细学习

Design and implementation of spark offline development framework

开发规范~参数校验异常、异常返回提示切面

双亲委派机制

ThreadLocal local thread

2022 safety officer-a certificate examination questions and answers

See how sparksql supports enterprise data warehouse
随机推荐
Research Report on market supply and demand and strategy of China's solar charging controller industry
shopee开店入驻流水如何提交?
【Mongodb】READ_ME_TO_RECOVER_YOUR_DATA,数据库被恶意删除
关于某手滑块的一些更新(6-18,js逆向)
C language operators and expressions
Win10 or win11 printer cannot print
Parental delegation mechanism
Simulated 100 questions and online simulated examination of high voltage electrician examination in 2022
High level application of SQL statements in MySQL database (I)
2022-06-16 work record --js- judge the number of digits in string type digits + judge the number of digits in numeric type digits + limit the text length (display n words at most, exceeding...)
Research Report on market supply and demand and strategy of ceiling power supply device industry in China
[laravel series 7.9] test
go Cobra命令行工具入门
[ingénierie logicielle] points clés à la fin de la période
2022 safety officer-a certificate examination questions and answers
vulnhub Vegeta: 1
Vulnhub Vegeta: 1
2022 simulated 100 questions and simulated examination of high-altitude installation, maintenance and demolition
Combine pod identity in aks and secret in CSI driver mount key vault
[QT] QT event handling