go?Cobra命令行工具入門教程
簡介
Github:https://github.com/spf13/
cobraStar:26.5K
Cobra是一個用Go語言實(shí)現(xiàn)的命令行工具。并且現(xiàn)在正在被很多項(xiàng)目使用,例如:Kubernetes、Hugo和Github CLI等。通過使用Cobra,我們可以快速的創(chuàng)建命令行工具,特別適合寫測試腳本,各種服務(wù)的Admin CLI等。比如 Mattermost 項(xiàng)目,就寫了很多 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 { // 導(dǎo)出到文件
// todo
} else if len(args) == 2 { // 導(dǎo)出...
// 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: "批量發(fā)送測試文本消息",
Long: ``,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("mockMsg called")
},
}
// 命令二
var exportCmd = &cobra.Command{
Use: "export",
Short: "導(dǎo)出數(shù)據(jù)",
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", "導(dǎo)出路徑")
}
func main() {
Execute()
}運(yùn)行:
$ go run main.go A longer description Usage: api [command] Available Commands: completion Generate the autocompletion script for the specified shell export 導(dǎo)出數(shù)據(jù) help Help about any command mockMsg 批量發(fā)送測試文本消息 Flags: -h, --help help for api -t, --toggle Help message for toggle Use "api [command] --help" for more information about a command.
發(fā)現(xiàn)了嗎?你不用再處理各種參數(shù)組合了,從此釋放了出來,只需要寫自己的業(yè)務(wù)邏輯即可!
基本概念
Cobra由三部分組成:
- 命令(Commands ):代表行為。命令是程序的中心點(diǎn),程序的每個功能都應(yīng)該可以通過命令進(jìn)行交互,一個命令可以有任意個子命令。
- 參數(shù)(Args):命令的參數(shù)
- 標(biāo)志(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
導(dǎo)入即可:
import "github.com/spf13/cobra"
命令行工具
建議安裝命令行工具 `cobra-cli` ,以方便快速創(chuàng)建cobra項(xiàng)目,增加command等。
# 命令行工具 $ go install github.com/spf13/cobra-cli@latest
安裝完成之后,執(zhí)行 `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.
入門實(shí)踐
新建cobra命令行程序
安裝了cobra-cli工具之后,執(zhí)行 init 初始化創(chuàng)建項(xiàng)目:
$ cobra-cli init
此時,在當(dāng)前目錄自動生成如下文件:
├── 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")
}此時運(yùn)行,不用指定參數(shù),會執(zhí)行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.
命令構(gòu)成
分析上面的默認(rèn)輸出:
- Available Commands:代表可以執(zhí)行的命令。比如./api connect
- Flags:是參數(shù)。比如./api connect --ip=127.0.0.1:6379,--ip就是flag,127.0.0.1:6379就是flag的值。
新增命令
我們來新增一個命令試試,這也是命令行程序的魅力,通過不同的參數(shù)執(zhí)行不同的動作。
語法:
$ cobra-cli add [command]
比如:
$ cobra-cli add mock-msg mockMsg created at /Users/xxx/repo/tools/api
此時,在cmd下會多一個文件(mock_msg.go),內(nèi)容如下:
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)
}再執(zhí)行rootCmd:
$ go build $ ./api
會發(fā)現(xiàn),多了一個命令:
// ... Available Commands: completion Generate the autocompletion script for the specified shell help Help about any command mockMsg A brief description of your command // ...
執(zhí)行mocMsg命令:
$ ./api mockMsg mockMsg called
此時,就可以在生成的mock_msg.go:Run() 函數(shù)中,放你自己的業(yè)務(wù)邏輯代碼了。
如何顯示自己的命令用法
上面新增了一個命令mockMsg,通過 ./api help 打印了命令和help,但是 `Use` 里面指定的內(nèi)容打印到哪里去了呢?這個時候,需要針對Command在指定help,此時就能打印這個命令的具體用法了。
./api mockMsg help 批量生產(chǎn)mq消息 Usage: benchmark mockmsg [flags] Flags: -g, --goroutine int32 并發(fā)routine數(shù)量 (default 1) -h, --help help for mockmsg -p, --packet int32 每個routine一秒寫入mq的數(shù)量 (default 20)
<br>-g和-p是新增的2個flag:
func init() {
mockmsgCmd.Flags().Int32P("goroutine", "g", 1, "并發(fā)routine數(shù)量")
mockmsgCmd.Flags().Int32P("packet", "p", 20, "每個routine一秒寫入mq的數(shù)量")
rootCmd.AddCommand(mockmsgCmd)
}獲取這2個值:
// mockmsgCmd represents the mockmsg command
var mockmsgCmd = &cobra.Command{
Use: "mockmsg",
Short: "批量生產(chǎn)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)
},
}執(zhí)行:
$ go run main.go mockmsg -p 322 -g 5 args1 args2 mockmsg called,flags:g= 5 ,p= 322 ,args: [args1 args2]
總結(jié)
我們通過一個例子,介紹了使用cobra帶來的好處。通過一個完整的入門實(shí)踐,演示了創(chuàng)建項(xiàng)目、添加命令和使用的一些示例,希望對你有所幫助!
參考:
https://blog.csdn.net/qq_31639829/article/details/118889580
https://github.com/mattermost/mattermost-server
到此這篇關(guān)于go Cobra命令行工具入門的文章就介紹到這了,更多相關(guān)go Cobra命令行工具內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go語言實(shí)現(xiàn)的可讀性更高的并發(fā)神庫詳解
這篇文章主要為大家介紹了Go語言實(shí)現(xiàn)的可讀性更高的并發(fā)神庫詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
Go檢查結(jié)構(gòu)體中是否存在某個字段及創(chuàng)建結(jié)構(gòu)體切片或映射
這篇文章主要為大家介紹了Go檢查結(jié)構(gòu)體中是否存在某個字段及創(chuàng)建結(jié)構(gòu)體切片或映射實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01
一文帶你了解Golang中interface的設(shè)計(jì)與實(shí)現(xiàn)
本文就來詳細(xì)說說為什么說?接口本質(zhì)是一種自定義類型,以及這種自定義類型是如何構(gòu)建起?go?的?interface?系統(tǒng)的,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-01-01
Golang?int函數(shù)使用實(shí)例全面教程
這篇文章主要為大家介紹了Golang?int函數(shù)使用實(shí)例全面教程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10
Go語言的Windows下環(huán)境配置以及簡單的程序結(jié)構(gòu)講解
這篇文章主要介紹了Go語言的Windows下環(huán)境配置以及簡單的程序結(jié)構(gòu)講解,從編程語言約定俗成的hellow world開始,需要的朋友可以參考下2015-10-10
vscode中安裝Go插件和配置Go環(huán)境詳細(xì)步驟
要在VSCode中配置Go語言插件,首先需要確保你的電腦已經(jīng)安裝了Go環(huán)境和最新版本的VSCode,這篇文章主要給大家介紹了關(guān)于vscode中安裝Go插件和配置Go環(huán)境的相關(guān)資料,需要的朋友可以參考下2024-01-01
golang?waitgroup輔助并發(fā)控制使用場景和方法解析
Golang?提供了簡潔的?go?關(guān)鍵字來讓開發(fā)者更容易的進(jìn)行并發(fā)編程,同時也提供了?WaitGroup?對象來輔助并發(fā)控制,今天我們就來分析下?WaitGroup?的使用方法,順便瞧一瞧它的底層源碼2023-09-09
一文帶你使用golang手?jǐn)]一個websocket中間件
這篇文章主要為大家詳細(xì)介紹了如何使用golang手?jǐn)]一個websocket中間件,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,感興趣的小伙伴可以參考一下2023-12-12

