最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

go?Cobra命令行工具入門教程

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

簡介

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

cobraStar:26.5K

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

為什么需要cobra

我們看一個(gè)簡單的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),程序的每個(gè)功能都應(yīng)該可以通過命令進(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` (請確保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

此時(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,打印使用說明:

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

新增命令

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

語法:

$ 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,通過 ./api help 打印了命令和help,但是 `Use` 里面指定的內(nèi)容打印到哪里去了呢?這個(gè)時(shí)候,需要針對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一秒寫入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一秒寫入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) {
      // 這里要寫全名
      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é)

我們通過一個(gè)例子,介紹了使用cobra帶來的好處。通過一個(gè)完整的入門實(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)文章

最新評論

上饶市| 深水埗区| 旌德县| 资源县| 阿拉善盟| 江源县| 庐江县| 蒙山县| 广宁县| 德钦县| 客服| 二连浩特市| 霸州市| 莱芜市| 怀来县| 万荣县| 庆城县| 临夏市| 滨州市| 洪泽县| 贵德县| 岳阳县| 乡宁县| 垫江县| 沂南县| 始兴县| 嘉义市| 广平县| 罗山县| 南木林县| 罗山县| 格尔木市| 兴安盟| 姜堰市| 霞浦县| 瑞昌市| 汉川市| 双柏县| 黄龙县| 麻江县| 长顺县|