当前位置:网站首页>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 :
边栏推荐
- Solve the problem of non secure websites requesting localhost to report CORS after chrome94
- Panorama of enterprise power in China SSD industry
- A big factory interview must ask: how to solve the problem of TCP reliable transmission? 8 pictures for you to learn in detail
- LeetCode Algorithm 剑指 Offer 52. 两个链表的第一个公共节点
- Do you need to improve your code reading ability? It's a trick
- Parental delegation mechanism
- 2022年高压电工考试模拟100题及在线模拟考试
- Research Report on research and investment prospects of China's container coating industry (2022 Edition)
- 【Laravel系列7.9】测试
- Tetris
猜你喜欢

【Mongodb】READ_ME_TO_RECOVER_YOUR_DATA,数据库被恶意删除

The usage difference between isempty and isblank is so different that so many people can't answer it

2022安全员-B证考试题库及答案

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

环境配置 | VS2017配置OpenMesh源码和环境
![[laravel series 7.9] test](/img/49/4b470a8b309bab4a83eed930dcce65.png)
[laravel series 7.9] test

2022 safety officer-a certificate examination questions and answers
![[postgraduate entrance examination English] prepare for 2023, learn list8 words](/img/25/d1f2c2b4c0958d381db87e5ef96df9.jpg)
[postgraduate entrance examination English] prepare for 2023, learn list8 words

Programmers become gods by digging holes in one year, carrying flags in five years and becoming gods in ten years

2022 simulated 100 questions and simulated examination of high-altitude installation, maintenance and demolition
随机推荐
CDN principle
docker安装mysql-简单无坑
2022-06-16 工作记录--JS-判断字符串型数字有几位 + 判断数值型数字有几位 + 限制文本长度(最多展示n个字,超出...)
New, Huawei cloud Kaitian apaas
Research Report on terahertz imaging system industry - market status analysis and development prospect forecast
[postgraduate entrance examination English] prepare for 2023, learn list9 words
LeetCode Algorithm 剑指 Offer II 027. 回文链表
ThreadLocal local thread
【Mongodb】READ_ME_TO_RECOVER_YOUR_DATA,数据库被恶意删除
How to integrate Huawei cloud function services in fluent
Research Report on solar battery charger industry - market status analysis and development prospect forecast
Leetcode: calculate the number of elements less than the current element on the right (sortedlist+bisect\u left)
Learn more about redis' eight data types and application scenario analysis
Analyze the implementation process of oauth2 distributed authentication and authorization based on the source code
别再乱用了,这才是 @Validated 和 @Valid 的真正区别!!!
vulnhub Vegeta: 1
C#学习两年的增删改查和C#导入导出(去重)案例
Epics record reference 3 -- fields common to all records
Problem solving - nested lists
canvas 实现图片新增水印