網站首頁 編程語言 正文
簡介
Github:https://github.com/spf13/
cobraStar:26.5K
Cobra是一個用Go語言實現的命令行工具。并且現在正在被很多項目使用,例如:Kubernetes、Hugo和Github CLI等。通過使用Cobra,我們可以快速的創建命令行工具,特別適合寫測試腳本,各種服務的Admin CLI等。比如 Mattermost 項目,就寫了很多 Admin CLI:
為什么需要cobra
我們看一個簡單的demo使用前
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.
發現了嗎?你不用再處理各種參數組合了,從此釋放了出來,只需要寫自己的業務邏輯即可!
基本概念
Cobra由三部分組成:
- 命令(Commands ):代表行為。命令是程序的中心點,程序的每個功能都應該可以通過命令進行交互,一個命令可以有任意個子命令。
- 參數(Args):命令的參數
- 標志(Flags):修飾命令。它修飾命令該如何完成。
官方推薦命令格式為:
$ ./appName command args --Flag
如 hugo server --port=1313 :
- appName: hugo?
- command: server?
- flag: port
安裝
Go pkg
添加依賴
$ go get -u github.com/spf13/cobra@latest
導入即可:
import "github.com/spf13/cobra"
命令行工具
建議安裝命令行工具 `cobra-cli` ,以方便快速創建cobra項目,增加command等。
# 命令行工具
$ go install github.com/spf13/cobra-cli@latest
安裝完成之后,執行 `cobra-cli --help` (請確保GOBIN已配置),輸出下列信息則代表成功:
$ 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命令行程序
安裝了cobra-cli工具之后,執行 init 初始化創建項目:
$ cobra-cli init
此時,在當前目錄自動生成如下文件:
├── LICENSE ├── cmd │ └── root.go └── main.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") }
此時運行,不用指定參數,會執行rootCmd,打印使用說明:
$ 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.
命令構成
分析上面的默認輸出:
- Available Commands:代表可以執行的命令。比如./api connect
- Flags:是參數。比如./api connect --ip=127.0.0.1:6379,--ip就是flag,127.0.0.1:6379就是flag的值。
新增命令
我們來新增一個命令試試,這也是命令行程序的魅力,通過不同的參數執行不同的動作。
語法:
$ cobra-cli add [command]
比如:
$ cobra-cli add mock-msg
mockMsg created at /Users/xxx/repo/tools/api
此時,在cmd下會多一個文件(mock_msg.go),內容如下:
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) }
再執行rootCmd:
$ 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
// ...
執行mocMsg命令:
$ ./api mockMsg
mockMsg called
此時,就可以在生成的mock_msg.go:Run() 函數中,放你自己的業務邏輯代碼了。
如何顯示自己的命令用法
上面新增了一個命令mockMsg,通過 ./api help 打印了命令和help,但是 `Use` 里面指定的內容打印到哪里去了呢?這個時候,需要針對Command在指定help,此時就能打印這個命令的具體用法了。
./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)
<br>-g和-p是新增的2個flag:
func init() { mockmsgCmd.Flags().Int32P("goroutine", "g", 1, "并發routine數量") mockmsgCmd.Flags().Int32P("packet", "p", 20, "每個routine一秒寫入mq的數量") rootCmd.AddCommand(mockmsgCmd) }
獲取這2個值:
// 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]
總結
我們通過一個例子,介紹了使用cobra帶來的好處。通過一個完整的入門實踐,演示了創建項目、添加命令和使用的一些示例,希望對你有所幫助!
參考:
https://blog.csdn.net/qq_31639829/article/details/118889580
https://github.com/mattermost/mattermost-server
原文鏈接:https://www.cnblogs.com/wishFreedom/p/16407894.html
相關推薦
- 2022-09-17 C/C++?中實現讓控制臺暫停的方法_C 語言
- 2022-09-25 Identity Server4/生產模式/證書/certificate/AddSigningCre
- 2022-03-16 ASP.NET?Core開發Docker部署_基礎應用
- 2023-02-12 Pytorch建模過程中的DataLoader與Dataset示例詳解_python
- 2022-10-12 Redis的共享session應用實現短信登錄_Redis
- 2022-04-20 從0編寫區塊鏈之用python解釋區塊鏈最基本原理_python
- 2022-04-10 關于C#中GUI編程的標準事件問題_C#教程
- 2022-07-04 PyTorch計算損失函數對模型參數的Hessian矩陣示例_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支