欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

go?Cobra命令行工具入門(mén)教程

 更新時(shí)間:2022年06月24日 10:53:03   作者:Go和分布式IM  
Cobra是一個(gè)用Go語(yǔ)言實(shí)現(xiàn)的命令行工具并且現(xiàn)在正在被很多項(xiàng)目使用,例如:Kubernetes、Hugo和Github?CLI等,通過(guò)使用Cobra,我們可以快速的創(chuàng)建命令行工具,特別適合寫(xiě)測(cè)試腳本,各種服務(wù)的Admin?CLI等,本文重點(diǎn)給大家介紹go?Cobra命令行工具,感興趣的朋友一起看看吧

簡(jiǎn)介

Github:https://github.com/spf13/

cobraStar:26.5K

Cobra是一個(gè)用Go語(yǔ)言實(shí)現(xiàn)的命令行工具。并且現(xiàn)在正在被很多項(xiàng)目使用,例如:Kubernetes、Hugo和Github CLI等。通過(guò)使用Cobra,我們可以快速的創(chuàng)建命令行工具,特別適合寫(xiě)測(cè)試腳本,各種服務(wù)的Admin CLI等。比如 Mattermost 項(xiàng)目,就寫(xiě)了很多 Admin CLI:

為什么需要cobra

我們看一個(gè)簡(jiǎn)單的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ā)送測(cè)試文本消息",
    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ā)送測(cè)試文本消息
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ù)組合了,從此釋放了出來(lái),只需要寫(xiě)自己的業(yè)務(wù)邏輯即可!

基本概念

Cobra由三部分組成:

  • 命令(Commands ):代表行為。命令是程序的中心點(diǎn),程序的每個(gè)功能都應(yīng)該可以通過(guò)命令進(jìn)行交互,一個(gè)命令可以有任意個(gè)子命令。
  • 參數(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` (請(qǐng)確保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.

  

入門(mén)實(shí)踐

新建cobra命令行程序

安裝了cobra-cli工具之后,執(zhí)行 init 初始化創(chuàng)建項(xiàng)目:

$ cobra-cli init

此時(shí),在當(dāng)前目錄自動(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")
}

此時(shí)運(yùn)行,不用指定參數(shù),會(huì)執(zhí)行rootCmd,打印使用說(shuō)明:

$ 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的值。

新增命令

我們來(lái)新增一個(gè)命令試試,這也是命令行程序的魅力,通過(guò)不同的參數(shù)執(zhí)行不同的動(dòng)作。

語(yǔ)法:

$ cobra-cli add [command]

比如:

$ cobra-cli add mock-msg
mockMsg created at /Users/xxx/repo/tools/api

此時(shí),在cmd下會(huì)多一個(gè)文件(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

會(huì)發(fā)現(xiàn),多了一個(gè)命令:

// ...
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

此時(shí),就可以在生成的mock_msg.go:Run() 函數(shù)中,放你自己的業(yè)務(wù)邏輯代碼了。

如何顯示自己的命令用法

上面新增了一個(gè)命令mockMsg,通過(guò) ./api help 打印了命令和help,但是 `Use` 里面指定的內(nèi)容打印到哪里去了呢?這個(gè)時(shí)候,需要針對(duì)Command在指定help,此時(shí)就能打印這個(gè)命令的具體用法了。

./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      每個(gè)routine一秒寫(xiě)入mq的數(shù)量 (default 20)

<br>-g和-p是新增的2個(gè)flag:

func init() {
   mockmsgCmd.Flags().Int32P("goroutine", "g", 1, "并發(fā)routine數(shù)量")
   mockmsgCmd.Flags().Int32P("packet", "p", 20, "每個(gè)routine一秒寫(xiě)入mq的數(shù)量")
  
   rootCmd.AddCommand(mockmsgCmd)
}

獲取這2個(gè)值:

// mockmsgCmd represents the mockmsg command
var mockmsgCmd = &cobra.Command{
   Use:   "mockmsg",
   Short: "批量生產(chǎn)mq消息",
   Run: func(cmd *cobra.Command, args []string) {
      // 這里要寫(xiě)全名
      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é)

我們通過(guò)一個(gè)例子,介紹了使用cobra帶來(lái)的好處。通過(guò)一個(gè)完整的入門(mén)實(shí)踐,演示了創(chuàng)建項(xiàng)目、添加命令和使用的一些示例,希望對(duì)你有所幫助!

參考:

https://blog.csdn.net/qq_31639829/article/details/118889580

https://github.com/mattermost/mattermost-server

到此這篇關(guān)于go Cobra命令行工具入門(mén)的文章就介紹到這了,更多相關(guān)go Cobra命令行工具內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • golang 的string與[]byte轉(zhuǎn)換方式

    golang 的string與[]byte轉(zhuǎn)換方式

    這篇文章主要介紹了golang 的string與[]byte轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-04-04
  • Golang高效解析和生成XML的示例詳解

    Golang高效解析和生成XML的示例詳解

    這篇文章將從Golang中處理XML的基本概念開(kāi)始,詳細(xì)介紹如何讀取和解析XML文件,然后轉(zhuǎn)向如何創(chuàng)建和輸出XML數(shù)據(jù),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-01-01
  • golang官方嵌入文件到可執(zhí)行程序的示例詳解

    golang官方嵌入文件到可執(zhí)行程序的示例詳解

    這篇文章主要介紹了golang官方嵌入文件到可執(zhí)行程序,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-02-02
  • 基于Go?goroutine實(shí)現(xiàn)一個(gè)簡(jiǎn)單的聊天服務(wù)

    基于Go?goroutine實(shí)現(xiàn)一個(gè)簡(jiǎn)單的聊天服務(wù)

    對(duì)于聊天服務(wù),想必大家都不會(huì)陌生,因?yàn)樵谖覀兊纳钪薪?jīng)常會(huì)用到,本文我們用?Go?并發(fā)來(lái)實(shí)現(xiàn)一個(gè)聊天服務(wù)器,這個(gè)程序可以讓一些用戶通過(guò)服務(wù)器向其它所有用戶廣播文本消息,文中通過(guò)代碼示例介紹的非常詳細(xì),需要的朋友可以參考下
    2023-06-06
  • golang 使用 viper 讀取自定義配置文件

    golang 使用 viper 讀取自定義配置文件

    這篇文章主要介紹了golang 使用 viper 讀取自定義配置文件,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-01-01
  • Golang WaitGroup實(shí)現(xiàn)原理解析

    Golang WaitGroup實(shí)現(xiàn)原理解析

    WaitGroup是Golang并發(fā)的兩種方式之一,一個(gè)是Channel,另一個(gè)是WaitGroup,下面這篇文章主要給大家介紹了關(guān)于golang基礎(chǔ)之waitgroup用法以及使用要點(diǎn)的相關(guān)資料,需要的朋友可以參考下
    2023-02-02
  • 以alpine作為基礎(chǔ)鏡像構(gòu)建Golang可執(zhí)行程序操作

    以alpine作為基礎(chǔ)鏡像構(gòu)建Golang可執(zhí)行程序操作

    這篇文章主要介紹了以alpine作為基礎(chǔ)鏡像構(gòu)建Golang可執(zhí)行程序操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-12-12
  • golang使用json格式實(shí)現(xiàn)增刪查改的實(shí)現(xiàn)示例

    golang使用json格式實(shí)現(xiàn)增刪查改的實(shí)現(xiàn)示例

    這篇文章主要介紹了golang使用json格式實(shí)現(xiàn)增刪查改的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • 詳解Go語(yǔ)言Slice作為函數(shù)參數(shù)的使用

    詳解Go語(yǔ)言Slice作為函數(shù)參數(shù)的使用

    Slice切片在Go語(yǔ)言中實(shí)質(zhì)是一種結(jié)構(gòu)體類(lèi)型,本文詳細(xì)的介紹了Go語(yǔ)言Slice作為函數(shù)參數(shù)的使用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-07-07
  • 詳解go?mod?使用方法

    詳解go?mod?使用方法

    golang 提供了 go mod命令來(lái)管理包,是go的一個(gè)模塊管理工具,用來(lái)代替?zhèn)鹘y(tǒng)的GOPATH方案,本文給大家介紹go?mod?使用方法,感興趣的朋友一起看看吧
    2022-05-05

最新評(píng)論