go?Cobra命令行工具入門教程
簡介
Github:https://github.com/spf13/
cobraStar:26.5K
Cobra是一個用Go語言實現(xiàn)的命令行工具。并且現(xiàn)在正在被很多項目使用,例如:Kubernetes、Hugo和Github CLI等。通過使用Cobra,我們可以快速的創(chuàng)建命令行工具,特別適合寫測試腳本,各種服務的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: "批量發(fā)送測試文本消息", Long: ``, Run: func(cmd *cobra.Command, args []string) { fmt.Println("mockMsg called") }, } // 命令二 var exportCmd = &cobra.Command{ Use: "export", Short: "導出數(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", "導出路徑") } 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 導出數(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è)務邏輯即可!
基本概念
Cobra由三部分組成:
- 命令(Commands ):代表行為。命令是程序的中心點,程序的每個功能都應該可以通過命令進行交互,一個命令可以有任意個子命令。
- 參數(shù)(Args):命令的參數(shù)
- 標志(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` ,以方便快速創(chuàng)建cobra項目,增加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.
入門實踐
新建cobra命令行程序
安裝了cobra-cli工具之后,執(zhí)行 init 初始化創(chuàng)建項目:
$ 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") }
此時運行,不用指定參數(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)成
分析上面的默認輸出:
- 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è)務邏輯代碼了。
如何顯示自己的命令用法
上面新增了一個命令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帶來的好處。通過一個完整的入門實踐,演示了創(chuà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)文章
golang 的string與[]byte轉(zhuǎn)換方式
這篇文章主要介紹了golang 的string與[]byte轉(zhuǎn)換方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04基于Go?goroutine實現(xiàn)一個簡單的聊天服務
對于聊天服務,想必大家都不會陌生,因為在我們的生活中經(jīng)常會用到,本文我們用?Go?并發(fā)來實現(xiàn)一個聊天服務器,這個程序可以讓一些用戶通過服務器向其它所有用戶廣播文本消息,文中通過代碼示例介紹的非常詳細,需要的朋友可以參考下2023-06-06以alpine作為基礎鏡像構(gòu)建Golang可執(zhí)行程序操作
這篇文章主要介紹了以alpine作為基礎鏡像構(gòu)建Golang可執(zhí)行程序操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12golang使用json格式實現(xiàn)增刪查改的實現(xiàn)示例
這篇文章主要介紹了golang使用json格式實現(xiàn)增刪查改的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05詳解Go語言Slice作為函數(shù)參數(shù)的使用
Slice切片在Go語言中實質(zhì)是一種結(jié)構(gòu)體類型,本文詳細的介紹了Go語言Slice作為函數(shù)參數(shù)的使用,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-07-07