当前位置:网站首页>Golang - command line tool Cobra
Golang - command line tool Cobra
2022-07-03 13:47:00 【The wind blows on the edge of the cloud】
List of articles
Cobra

Cobra Is a Go Linguistic CLI frame . It contains a for creating powerful modern CLI The library of the application , And one for rapid generation based on Cobra Tools for applications and command files .
characteristic
- Simple subcommand mode , Such as app server, app fetch wait
- Fully compatible with posix Command line mode
- Nested sub command subcommand
- Support the overall situation , Local , Series connection flags
- Use cobra It's easy to generate applications and commands , Use cobra create appname and cobra add cmdname
- If the command is entered incorrectly , Intelligent advice will be provided , Such as app srver, Will prompt srver No, , Is it right? app server
- Automatic generation commands and flags Help for
- Automatically generate detailed help Information , Such as app help
- Automatic recognition help flag -h,–help
- Auto generate application in bash Command auto complete function
- Automatically generate application man manual
- Command line alias
- Customize help and usage Information
- Optional and viper apps The tight integration of
Concept
Cobra Is based on the command 、 The structure of parameters and signs .
Commands It's for action ,Args It's something ,Flags It's the modifier for these actions .
The best application reads like a sentence . Users will know how to use the application , Because they are born to know how to use it .
for example :
hugo server --port=1313
Command
Command Is the central point of the application . Every interaction supported by the application is contained in Command in . Commands can have subcommands , You can also operate selectively .
Flag
flag Is a way to modify command behavior .Cobra Fully support compatibility posix The logo and Go Logo pack .Cobra Commands can define flags that run through subcommands , And flags that are only available for this command .
In the example above --port It's a flag
Global identity (Persistent Flags)
Global identity (Persistent Flags) It will act on its specified command and all subcommands of the specified command .
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
Local identification (Local Flags)
Local marking (Local Flags) Only works on its specified command .
rootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
Run Hooks
Can be in the main command run Run the function before or after the function .PersistentPreRun and PreRun The function will be in Run Before execution .persistentpoststrun and poststrun Will be in Run After performing . If the subclass does not declare its own Persistent*Run function , They will be inherited by subclasses . These functions run in the following order :
- PersistentPreRun
- PreRun
- Run
- PostRun
- PersistentPostRun
Example :
package main
import (
"fmt"
"github.com/spf13/cobra"
)
func main() {
var rootCmd = &cobra.Command{
Use: "root [sub]",
Short: "My root command",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
},
PreRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
},
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside rootCmd Run with args: %v\n", args)
},
PostRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
},
}
var subCmd = &cobra.Command{
Use: "sub [no options!]",
Short: "My subcommand",
PreRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
},
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside subCmd Run with args: %v\n", args)
},
PostRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
},
}
rootCmd.AddCommand(subCmd)
rootCmd.SetArgs([]string{
""})
rootCmd.Execute()
fmt.Println()
rootCmd.SetArgs([]string{
"sub", "arg1", "arg2"})
rootCmd.Execute()
}
output:
Inside rootCmd PersistentPreRun with args: []
Inside rootCmd PreRun with args: []
Inside rootCmd Run with args: []
Inside rootCmd PostRun with args: []
Inside rootCmd PersistentPostRun with args: []
Inside rootCmd PersistentPreRun with args: [arg1 arg2]
Inside subCmd PreRun with args: [arg1 arg2]
Inside subCmd Run with args: [arg1 arg2]
Inside subCmd PostRun with args: [arg1 arg2]
Inside subCmd PersistentPostRun with args: [arg1 arg2]
边栏推荐
- Tutoriel PowerPoint, comment enregistrer une présentation sous forme de vidéo dans Powerpoint?
- MyCms 自媒体商城 v3.4.1 发布,使用手册更新
- JS 将伪数组转换成数组
- Bidirectional linked list (we only need to pay attention to insert and delete functions)
- mysql中的字段问题
- Kivy tutorial how to automatically load kV files
- rxjs Observable filter Operator 的实现原理介绍
- Resource Cost Optimization Practice of R & D team
- Comprehensive evaluation of double chain notes remnote: fast input, PDF reading, interval repetition / memory
- Screenshot of the operation steps of upload labs level 4-level 9
猜你喜欢

Comprehensively develop the main channel of digital economy and digital group, and actively promote the utonmos digital Tibet market

MySQL

Internet of things completion -- (stm32f407 connects to cloud platform detection data)

Resolved (error in viewing data information in machine learning) attributeerror: target_ names

Error running 'application' in idea running: the solution of command line is too long

Logseq 评测:优点、缺点、评价、学习教程

Servlet

Bidirectional linked list (we only need to pay attention to insert and delete functions)

File uploading and email sending
![[redis] cache warm-up, cache avalanche and cache breakdown](/img/df/81f38087704de36946b470f68e8004.jpg)
[redis] cache warm-up, cache avalanche and cache breakdown
随机推荐
Universal dividend source code, supports the dividend of any B on the BSC
Setting up remote links to MySQL on Linux
Convolution emotion analysis task4
Comprehensive evaluation of double chain notes remnote: fast input, PDF reading, interval repetition / memory
Shell timing script, starting from 0, CSV format data is regularly imported into PostgreSQL database shell script example
untiy世界边缘的物体阴影闪动,靠近远点的物体阴影正常
File uploading and email sending
JS convert pseudo array to array
掌握Cypress命令行选项,是真正掌握Cypress的基础
Replace the GPU card number when pytorch loads the historical model, map_ Location settings
Mastering the cypress command line options is the basis for truly mastering cypress
NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
Ocean CMS vulnerability - search php
SQL Injection (POST/Select)
php 迷宫游戏
实现CNN图像的识别和训练通过tensorflow框架对cifar10数据集等方法的处理
Flutter dynamic | fair 2.5.0 new version features
106. How to improve the readability of SAP ui5 application routing URL
IBEM mathematical formula detection data set
Open PHP error prompt under Ubuntu 14.04