激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Golang - golang中命令行庫cobra的使用方法示例

golang中命令行庫cobra的使用方法示例

2020-05-18 11:03wangbin Golang

這篇文章主要給大家介紹了關于golang中命令行庫cobra的使用方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

簡介

Cobra既是一個用來創建強大的現代CLI命令行的golang庫,也是一個生成程序應用和命令行文件的程序。下面是Cobra使用的一個演示:

golang中命令行庫cobra的使用方法示例

Cobra提供的功能

  • 簡易的子命令行模式,如 app server, app fetch等等
  • 完全兼容posix命令行模式
  • 嵌套子命令subcommand
  • 支持全局,局部,串聯flags
  • 使用Cobra很容易的生成應用程序和命令,使用cobra create appname和cobra add cmdname
  • 如果命令輸入錯誤,將提供智能建議,如 app srver,將提示srver沒有,是否是app server
  • 自動生成commands和flags的幫助信息
  • 自動生成詳細的help信息,如app help
  • 自動識別-h,--help幫助flag
  • 自動生成應用程序在bash下命令自動完成功能
  • 自動生成應用程序的man手冊
  • 命令行別名
  • 自定義help和usage信息
  • 可選的緊密集成的viper apps

如何使用

上面所有列出的功能我沒有一一去使用,下面我來簡單介紹一下如何使用Cobra,基本能夠滿足一般命令行程序的需求,如果需要更多功能,可以研究一下源碼github。

安裝cobra

Cobra是非常容易使用的,使用go get來安裝最新版本的庫。當然這個庫還是相對比較大的,可能需要安裝它可能需要相當長的時間,這取決于你的速網。安裝完成后,打開GOPATH目錄,bin目錄下應該有已經編譯好的cobra.exe程序,當然你也可以使用源代碼自己生成一個最新的cobra程序。

?
1
> go get -v github.com/spf13/cobra/cobra

使用cobra生成應用程序

假設現在我們要開發一個基于CLIs的命令程序,名字為demo。首先打開CMD,切換到GOPATH的src目錄下[^1],執行如下指令:
[^1]:cobra.exe只能在GOPATH目錄下執行

?
1
2
3
4
5
src> ..\bin\cobra.exe init demo
Your Cobra application is ready at
C:\Users\liubo5\Desktop\transcoding_tool\src\demo
Give it a try by going there and running `go run main.go`
Add commands to it by running `cobra add [cmdname]`

在src目錄下會生成一個demo的文件夾,如下:

? demo
    ? cmd/
        root.go
    main.go

如果你的demo程序沒有subcommands,那么cobra生成應用程序的操作就結束了。

如何實現沒有子命令的CLIs程序

接下來就是可以繼續demo的功能設計了。例如我在demo下面新建一個包,名稱為imp。如下:

? demo
    ? cmd/
        root.go
    ? imp/
        imp.go
        imp_test.go
    main.go

imp.go文件的代碼如下:

?
1
2
3
4
5
6
7
8
9
package imp
 
import(
 "fmt"
)
 
func Show(name string, age int) {
 fmt.Printf("My Name is %s, My age is %d\n", name, age)
}

demo程序成命令行接收兩個參數name和age,然后打印出來。打開cobra自動生成的main.go文件查看:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
 
package main
 
import "demo/cmd"
 
func main() {
 cmd.Execute()
}

可以看出main函數執行cmd包,所以我們只需要在cmd包內調用imp包就能實現demo程序的需求。接著打開root.go文件查看:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
 
package cmd
 
import (
 "fmt"
 "os"
 
 "github.com/spf13/cobra"
 "github.com/spf13/viper"
)
 
var cfgFile string
 
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
 Use: "demo",
 Short: "A brief description of your application",
 Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
 
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.`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}
 
// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
 if err := RootCmd.Execute(); err != nil {
  fmt.Println(err)
  os.Exit(-1)
 }
}
 
func init() {
 cobra.OnInitialize(initConfig)
 
 // Here you will define your flags and configuration settings.
 // Cobra supports Persistent Flags, which, if defined here,
 // will be global for your application.
 
 RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.demo.yaml)")
 // Cobra also supports local flags, which will only run
 // when this action is called directly.
 RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
 
// initConfig reads in config file and ENV variables if set.
func initConfig() {
 if cfgFile != "" { // enable ability to specify config file via flag
  viper.SetConfigFile(cfgFile)
 }
 
 viper.SetConfigName(".demo") // name of config file (without extension)
 viper.AddConfigPath("$HOME") // adding home directory as first search path
 viper.AutomaticEnv()   // read in environment variables that match
 
 // If a config file is found, read it in.
 if err := viper.ReadInConfig(); err == nil {
  fmt.Println("Using config file:", viper.ConfigFileUsed())
 }
}

從源代碼來看cmd包進行了一些初始化操作并提供了Execute接口。十分簡單,其中viper是cobra集成的配置文件讀取的庫,這里不需要使用,我們可以注釋掉(不注釋可能生成的應用程序很大約10M,這里沒喲用到最好是注釋掉)。cobra的所有命令都是通過cobra.Command這個結構體實現的。為了實現demo功能,顯然我們需要修改RootCmd。修改后的代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
 
package cmd
 
import (
 "fmt"
 "os"
 
 "github.com/spf13/cobra"
 // "github.com/spf13/viper"
 "demo/imp"
)
 
//var cfgFile string
var name string
var age int
 
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
 Use: "demo",
 Short: "A test demo",
 Long: `Demo is a test appcation for print things`,
 // Uncomment the following line if your bare application
 // has an action associated with it:
 Run: func(cmd *cobra.Command, args []string) {
  if len(name) == 0 {
   cmd.Help()
   return
  }
  imp.Show(name, age)
 },
}
 
// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
 if err := RootCmd.Execute(); err != nil {
  fmt.Println(err)
  os.Exit(-1)
 }
}
 
func init() {
 // cobra.OnInitialize(initConfig)
 
 // Here you will define your flags and configuration settings.
 // Cobra supports Persistent Flags, which, if defined here,
 // will be global for your application.
 
 // RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.demo.yaml)")
 // Cobra also supports local flags, which will only run
 // when this action is called directly.
 // RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
 RootCmd.Flags().StringVarP(&name, "name", "n", "", "person's name")
 RootCmd.Flags().IntVarP(&age, "age", "a", 0, "person's age")
}
 
// initConfig reads in config file and ENV variables if set.
//func initConfig() {
// if cfgFile != "" { // enable ability to specify config file via flag
//  viper.SetConfigFile(cfgFile)
// }
 
// viper.SetConfigName(".demo") // name of config file (without extension)
// viper.AddConfigPath("$HOME") // adding home directory as first search path
// viper.AutomaticEnv()   // read in environment variables that match
 
// // If a config file is found, read it in.
// if err := viper.ReadInConfig(); err == nil {
//  fmt.Println("Using config file:", viper.ConfigFileUsed())
// }
//}

到此demo的功能已經實現了,我們編譯運行一下看看實際效果:

>demo.exe
Demo is a test appcation for print things

Usage:
  demo [flags]

Flags:
  -a, --age int       person's age
  -h, --help          help for demo
  -n, --name string   person's name

>demo -n borey --age 26
My Name is borey, My age is 26

如何實現帶有子命令的CLIs程序

在執行cobra.exe init demo之后,繼續使用cobra為demo添加子命令test:

?
1
2
src\demo>..\..\bin\cobra add test
test created at C:\Users\liubo5\Desktop\transcoding_tool\src\demo\cmd\test.go

在src目錄下demo的文件夾下生成了一個cmd\test.go文件,如下:

? demo
    ? cmd/
        root.go
        test.go
    main.go

接下來的操作就和上面修改root.go文件一樣去配置test子命令。效果如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
src\demo>demo
Demo is a test appcation for print things
 
Usage:
 demo [flags]
 demo [command]
 
Available Commands:
 test  A brief description of your command
 
Flags:
 -a, --age int  person's age
 -h, --help   help for demo
 -n, --name string person's name
 
Use "demo [command] --help" for more information about a command.

可以看出demo既支持直接使用標記flag,又能使用子命令

?
1
2
3
4
5
6
7
8
9
10
src\demo>demo test -h
A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
 
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:
 demo test [flags]

調用test命令輸出信息,這里沒有對默認信息進行修改。

?
1
2
3
4
5
6
7
8
9
10
11
src\demo>demo tst
Error: unknown command "tst" for "demo"
 
Did you mean this?
  test
 
Run 'demo --help' for usage.
unknown command "tst" for "demo"
 
Did you mean this?
  test

這是錯誤命令提示功能

OVER

Cobra的使用就介紹到這里,更新細節可去github詳細研究一下。這里只是一個簡單的使用入門介紹,如果有錯誤之處,敬請指出,謝謝~

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。

原文鏈接:https://studygolang.com/articles/14187

延伸 · 閱讀

精彩推薦
  • GolangGolang中Bit數組的實現方式

    Golang中Bit數組的實現方式

    這篇文章主要介紹了Golang中Bit數組的實現方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧...

    天易獨尊11682021-06-09
  • Golanggolang 通過ssh代理連接mysql的操作

    golang 通過ssh代理連接mysql的操作

    這篇文章主要介紹了golang 通過ssh代理連接mysql的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧...

    a165861639710342021-03-08
  • Golanggolang如何使用struct的tag屬性的詳細介紹

    golang如何使用struct的tag屬性的詳細介紹

    這篇文章主要介紹了golang如何使用struct的tag屬性的詳細介紹,從例子說起,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看...

    Go語言中文網11352020-05-21
  • Golanggolang json.Marshal 特殊html字符被轉義的解決方法

    golang json.Marshal 特殊html字符被轉義的解決方法

    今天小編就為大家分享一篇golang json.Marshal 特殊html字符被轉義的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧 ...

    李浩的life12792020-05-27
  • Golanggo語言制作端口掃描器

    go語言制作端口掃描器

    本文給大家分享的是使用go語言編寫的TCP端口掃描器,可以選擇IP范圍,掃描的端口,以及多線程,有需要的小伙伴可以參考下。 ...

    腳本之家3642020-04-25
  • Golanggolang的httpserver優雅重啟方法詳解

    golang的httpserver優雅重啟方法詳解

    這篇文章主要給大家介紹了關于golang的httpserver優雅重啟的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,...

    helight2992020-05-14
  • Golanggo日志系統logrus顯示文件和行號的操作

    go日志系統logrus顯示文件和行號的操作

    這篇文章主要介紹了go日志系統logrus顯示文件和行號的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧...

    SmallQinYan12302021-02-02
  • GolangGolang通脈之數據類型詳情

    Golang通脈之數據類型詳情

    這篇文章主要介紹了Golang通脈之數據類型,在編程語言中標識符就是定義的具有某種意義的詞,比如變量名、常量名、函數名等等,Go語言中標識符允許由...

    4272021-11-24
主站蜘蛛池模板: 国产精品视频yy9299一区 | 免费a视频在线观看 | 色淫湿视频 | 欧美日韩手机在线观看 | 在线a毛片 | h色视频在线观看 | 亚洲国产精品高潮呻吟久久 | 色网站在线免费观看 | 在线视频欧美一区 | 视频一区免费观看 | 手机av免费电影 | 毛片视频免费观看 | 国产无遮挡一区二区三区毛片日本 | 国产成人高清在线观看 | 国产盼盼私拍福利视频99 | 国产亚洲高清在线精品不卡 | 久久精品视频一区二区三区 | 成人在线视频在线观看 | 九一免费版在线观看 | 亚洲二区不卡 | 久久在线免费视频 | 久久精品国产99久久6动漫亮点 | 日本在线视频二区 | 日韩中文一区 | 99精品视频免费看 | 毛片国产 | av在线久草 | 性欧美视频在线观看 | 国产精品视频专区 | 久久久久久久黄色片 | 毛片免费在线 | 中文字幕电影免费播放 | 欧美一级α片 | 久久亚洲精品国产一区 | 成人情欲视频在线看免费 | 一区在线视频观看 | 午夜精品久久久久久中宇 | 亚洲欧美日韩一区二区三区在线观看 | 正在播放91视频 | 香蕉视频99 | 欧美精品成人一区二区三区四区 |