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

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

 更新時(shí)間:2018年08月14日 10:11:05   作者:wangbin  
這篇文章主要給大家介紹了關(guān)于golang中命令行庫cobra的使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

簡介

Cobra既是一個(gè)用來創(chuàng)建強(qiáng)大的現(xiàn)代CLI命令行的golang庫,也是一個(gè)生成程序應(yīng)用和命令行文件的程序。下面是Cobra使用的一個(gè)演示:

Cobra提供的功能

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

如何使用

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

安裝cobra

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

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

使用cobra生成應(yīng)用程序

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

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目錄下會(huì)生成一個(gè)demo的文件夾,如下:

▾ demo
    ▾ cmd/
        root.go
    main.go

如果你的demo程序沒有subcommands,那么cobra生成應(yīng)用程序的操作就結(jié)束了。

如何實(shí)現(xiàn)沒有子命令的CLIs程序

接下來就是可以繼續(xù)demo的功能設(shè)計(jì)了。例如我在demo下面新建一個(gè)包,名稱為imp。如下:

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

imp.go文件的代碼如下:

package imp

import(
 "fmt"
)

func Show(name string, age int) {
 fmt.Printf("My Name is %s, My age is %d\n", name, age)
}

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

// 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函數(shù)執(zhí)行cmd包,所以我們只需要在cmd包內(nèi)調(diào)用imp包就能實(shí)現(xiàn)demo程序的需求。接著打開root.go文件查看:

// 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包進(jìn)行了一些初始化操作并提供了Execute接口。十分簡單,其中viper是cobra集成的配置文件讀取的庫,這里不需要使用,我們可以注釋掉(不注釋可能生成的應(yīng)用程序很大約10M,這里沒喲用到最好是注釋掉)。cobra的所有命令都是通過cobra.Command這個(gè)結(jié)構(gòu)體實(shí)現(xiàn)的。為了實(shí)現(xiàn)demo功能,顯然我們需要修改RootCmd。修改后的代碼如下:

// 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的功能已經(jīng)實(shí)現(xiàn)了,我們編譯運(yùn)行一下看看實(shí)際效果:

>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

如何實(shí)現(xiàn)帶有子命令的CLIs程序

在執(zhí)行cobra.exe init demo之后,繼續(xù)使用cobra為demo添加子命令test:

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

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

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

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

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既支持直接使用標(biāo)記flag,又能使用子命令

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]

調(diào)用test命令輸出信息,這里沒有對默認(rèn)信息進(jìn)行修改。

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

這是錯(cuò)誤命令提示功能

OVER

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

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關(guān)文章

  • GO比較兩個(gè)對象是否相同實(shí)戰(zhàn)案例

    GO比較兩個(gè)對象是否相同實(shí)戰(zhàn)案例

    我們時(shí)常有比較兩個(gè)值是否相等的需求,下面這篇文章主要給大家介紹了關(guān)于GO比較兩個(gè)對象是否相同的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-12-12
  • Golang中println和fmt.Println區(qū)別解析

    Golang中println和fmt.Println區(qū)別解析

    Golang 中打印數(shù)據(jù)通常使用 fmt.Println() 方法,也可以使用內(nèi)置的 println() 方法。這兩個(gè)方法大家可能都使用過,它們的區(qū)別是什么呢?本文給大家詳細(xì)講解,感興趣的朋友跟隨小編一起看看吧
    2023-03-03
  • 詳解Go語言中iota的應(yīng)用

    詳解Go語言中iota的應(yīng)用

    在本文中,小編將帶著大家深入探討?iota?的神奇力量,包括?iota?的介紹和應(yīng)用場景以及使用技巧和注意事項(xiàng),準(zhǔn)備好了嗎,準(zhǔn)備一杯你最喜歡的飲料或茶,隨著本文一探究竟吧
    2023-07-07
  • Go單例模式與Once源碼實(shí)現(xiàn)

    Go單例模式與Once源碼實(shí)現(xiàn)

    這篇文章主要介紹了Go單例模式與Once源碼實(shí)現(xiàn),本文結(jié)合示例代碼給大家講解的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-12-12
  • go語言int64整型轉(zhuǎn)字符串的實(shí)現(xiàn)

    go語言int64整型轉(zhuǎn)字符串的實(shí)現(xiàn)

    本文主要介紹了go語言int64整型轉(zhuǎn)字符串的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • 詳解go語言是如何實(shí)現(xiàn)協(xié)程的

    詳解go語言是如何實(shí)現(xiàn)協(xié)程的

    go語言的精華就在于協(xié)程的設(shè)計(jì),只有理解協(xié)程的設(shè)計(jì)思想和工作機(jī)制,才能確保我們能夠完全的利用協(xié)程編寫強(qiáng)大的并發(fā)程序,所以本文將給大家介紹了go語言是如何實(shí)現(xiàn)協(xié)程的,文中有詳細(xì)的代碼講解,需要的朋友可以參考下
    2024-04-04
  • 模塊一 GO語言基礎(chǔ)知識(shí)-庫源碼文件

    模塊一 GO語言基礎(chǔ)知識(shí)-庫源碼文件

    這篇文章主要介紹了模塊一 GO語言基礎(chǔ)知識(shí)-庫源碼文件,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-01-01
  • 使用golang進(jìn)行http,get或postJson請求

    使用golang進(jìn)行http,get或postJson請求

    這篇文章主要為大家詳細(xì)介紹了如何使用golang進(jìn)行http,get或postJson請求,文中的示例代碼簡潔易懂,具有一定的借鑒價(jià)值,感興趣的小伙伴可以了解一下
    2023-12-12
  • go語言寫的簡要數(shù)據(jù)同步工具詳解

    go語言寫的簡要數(shù)據(jù)同步工具詳解

    作為go-etl工具的作者,想要安利一下這個(gè)小巧的數(shù)據(jù)同步工具,它在同步百萬級(jí)別的數(shù)據(jù)時(shí)表現(xiàn)極為優(yōu)異,基本能在幾分鐘完成數(shù)據(jù)同步,這篇文章主要介紹了go語言寫的簡要數(shù)據(jù)同步工具,需要的朋友可以參考下
    2024-07-07
  • 一個(gè)Pod調(diào)度失敗后重新觸發(fā)調(diào)度的所有情況分析

    一個(gè)Pod調(diào)度失敗后重新觸發(fā)調(diào)度的所有情況分析

    這篇文章主要為大家介紹了一個(gè)Pod調(diào)度失敗后重新觸發(fā)調(diào)度的所有情況分析詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-04-04

最新評(píng)論

界首市| 淄博市| 长岛县| 长海县| 镇雄县| 浙江省| 冕宁县| 义乌市| 乾安县| 浙江省| 山丹县| 东至县| 浠水县| 建宁县| 成都市| 年辖:市辖区| 湘潭县| 温泉县| 温泉县| 高清| 建宁县| 蒙阴县| 遵义市| 尼玛县| 毕节市| 北辰区| 贵德县| 固原市| 合川市| 泗阳县| 建昌县| 潞西市| 江安县| 杂多县| 镇平县| 溧水县| 林周县| 新民市| 稻城县| 高清| 永川市|