golang編程cobra-cli庫(kù)使用

1、準(zhǔn)備

1.1 資源和文檔
1.2 下載

使用 go get命令下載:

go get -u github.com/spf13/cobra

2、使用

2.1 基本使用
  • 在工程中新建cmd文件夾,并添加root命令:在cmd文件夾下新建root.go文件,內(nèi)容如下:
package cmd

import (
    "fmt"
    "github.com/spf13/cobra"
    "os"
)

var rootCmd = &cobra.Command{
    Use: "CobraExample",
    Short: "cobra use example",
    Long: `An application show how to use cobra library.
Author:roc
Blog:makerinchina.cn`,

}

func Excute() {
    if err:= rootCmd.Execute(); err!=nil {
        fmt.Println(err)
        os.Exit(1)
    }
}
  • 然后在main函數(shù)中執(zhí)行,main.go 文件內(nèi)容如下:
package main

import "cli_cobra_example/cmd"

func main() {
    cmd.Excute()
}

  • 測(cè)試

執(zhí)行 go build,編譯程序,然后執(zhí)行可以看到如下輸出:

An application show how to use cobra library.
Author:roc
Blog:makerinchina.cn
2.2 添加自己的命令

有了第一步的基礎(chǔ)后,我們可以添加自己的命令,這里添加一個(gè)test命令,執(zhí)行后輸出test提示。

  • 先在cmd文件夾下新建test.go 文件,內(nèi)容如下:
package cmd

import (
    "fmt"
    "github.com/spf13/cobra"
)

var testCmd = &cobra.Command{
    Use: "testCmd",
    Short: "A test cmd",
    Run: testCmdFunc,
}

func testCmdFunc(cmd *cobra.Command, args []string) {
    fmt.Println("test cmd function execute.")

    if len(args) > 0 {
        i := 0
        for i=0;i<len(args);i++ {

            fmt.Printf("  args[%d]:%s\r\n", i, args[i])

        }

    }
}

func init() {
    rootCmd.AddCommand(testCmd)
}

此時(shí)編譯后執(zhí)行程序輸出如下:

An application show how to use cobra library.
Author:roc
Blog:makerinchina.cn

Usage:
  CobraExample [command]

Available Commands:
  help        Help about any command
  testCmd     A test cmd

Flags:
  -h, --help   help for CobraExample

Use "CobraExample [command] --help" for more information about a command.

如果執(zhí)行程序帶上命令和參數(shù): app testCmd arg1 arg2, 則輸出如下:

test cmd function execute.
  args[0]:arg1
  args[1]:arg2

2.3 使用命令標(biāo)志Flags

(1) 全局命令標(biāo)志

這種標(biāo)志定義后會(huì)作用于定義它的命令和它的子命令。

  • 在root.go文件添加flags:
package cmd

import (
    "fmt"
    "github.com/spf13/cobra"
    "os"
)

var rootCmd = &cobra.Command{
    Use: "CobraExample",
    Short: "cobra use example",
    Long: `An application show how to use cobra library.
Author:roc
Blog:makerinchina.cn`,
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("root cmd execute function.")


    },
}

var flags1 string

func init() {
    rootCmd.PersistentFlags().StringVarP(&flags1,"flags1","f","default value","flag defined in rootcmd.")
}

func Excute() {
    if err:= rootCmd.Execute(); err!=nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

執(zhí)行程序并帶 -h 參數(shù)輸出如下:

An application show how to use cobra library.
Author:roc
Blog:makerinchina.cn

Usage:
  CobraExample [flags]
  CobraExample [command]

Available Commands:
  help        Help about any command
  testCmd     A test cmd

Flags:
  -f, --flags1 string   flag defined in rootcmd. (default "default value")
  -h, --help            help for CobraExample

Use "CobraExample [command] --help" for more information about a command.

然后執(zhí)行程序并帶子命令參數(shù): app testCmd -h,也會(huì)有-f的標(biāo)志,輸出如下:

A test cmd

Usage:
  CobraExample testCmd [flags]

Flags:
  -h, --help   help for testCmd

Global Flags:
  -f, --flags1 string   flag defined in rootcmd. (default "default value")

(2) 特定命令標(biāo)志

這種標(biāo)志僅僅用于定義它的命令。

  • 修改test.go文件如下:
package cmd

import (
    "fmt"
    "github.com/spf13/cobra"
)

var testCmd = &cobra.Command{
    Use: "testCmd",
    Short: "A test cmd",
    Run: testCmdFunc,
}

var testFlag1 string

func testCmdFunc(cmd *cobra.Command, args []string) {
    fmt.Println("test cmd function execute.")

    if len(args) > 0 {
        i := 0
        for i=0;i<len(args);i++ {

            fmt.Printf("  args[%d]:%s\r\n", i, args[i])

        }

    }

    strflag, _ := cmd.Flags().GetString("testflag")
    fmt.Println("local cmd flags:", strflag)

    strflagroot, _ := rootCmd.Flags().GetString("flags1")
    fmt.Println("root cmd flags:", strflagroot)
}

func init() {
    rootCmd.AddCommand(testCmd)

    testCmd.Flags().StringVarP(&testFlag1,"testflag","t","default value1", "test cmd flag1")
}
  • 執(zhí)行子命令 testCmd:
app testCmd -h 

可以看到輸出如下:

A test cmd

Usage:
  CobraExample testCmd [flags]

Flags:
  -h, --help              help for testCmd
  -t, --testflag string   test cmd flag1 (default "default value1")

Global Flags:
  -f, --flags1 string   flag defined in rootcmd. (default "default value")
  • 執(zhí)行命令并輸出標(biāo)志參數(shù):
app  testCmd arg1 -f global_flag -t local_flag

輸出結(jié)果如下:

test cmd function execute.
  args[0]:arg1
local cmd flags: local_flag
root cmd flags: global_flag
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容