golang编程cobra-cli库使用

1、准备

1.1 资源和文档
  • 库:https://github.com/spf13/cobra
  • 文档:https://github.com/spf13/cobra/blob/master/README.md
1.2 下载

使用 go get命令下载:

go get -u github.com/spf13/cobra

2、使用

2.1 基本使用
  • 在工程中新建cmd文件夹,并添加root命令:在cmd文件夹下新建root.go文件,内容如下:
package cmdimport ("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函数中执行,main.go 文件内容如下:
package mainimport "cli_cobra_example/cmd"func main() {cmd.Excute()
}
  • 测试

执行 go build,编译程序,然后执行可以看到如下输出:

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

有了第一步的基础后,我们可以添加自己的命令,这里添加一个test命令,执行后输出test提示。

  • 先在cmd文件夹下新建test.go 文件,内容如下:
package cmdimport ("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 := 0for i=0;i<len(args);i++ {fmt.Printf("  args[%d]:%s\r\n", i, args[i])}}
}func init() {rootCmd.AddCommand(testCmd)
}

此时编译后执行程序输出如下:

An application show how to use cobra library.
Author:roc
Blog:makerinchina.cnUsage:CobraExample [command]Available Commands:help        Help about any commandtestCmd     A test cmdFlags:-h, --help   help for CobraExampleUse "CobraExample [command] --help" for more information about a command.

如果执行程序带上命令和参数: app testCmd arg1 arg2, 则输出如下:

test cmd function execute.args[0]:arg1args[1]:arg2
2.3 使用命令标志Flags

(1) 全局命令标志

这种标志定义后会作用于定义它的命令和它的子命令。

  • 在root.go文件添加flags:
package cmdimport ("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 stringfunc 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)}
}

执行程序并带 -h 参数输出如下:

An application show how to use cobra library.
Author:roc
Blog:makerinchina.cnUsage:CobraExample [flags]CobraExample [command]Available Commands:help        Help about any commandtestCmd     A test cmdFlags:-f, --flags1 string   flag defined in rootcmd. (default "default value")-h, --help            help for CobraExampleUse "CobraExample [command] --help" for more information about a command.

然后执行程序并带子命令参数: app testCmd -h,也会有-f的标志,输出如下:

A test cmdUsage:CobraExample testCmd [flags]Flags:-h, --help   help for testCmdGlobal Flags:-f, --flags1 string   flag defined in rootcmd. (default "default value")

(2) 特定命令标志

这种标志仅仅用于定义它的命令。

  • 修改test.go文件如下:
package cmdimport ("fmt""github.com/spf13/cobra"
)var testCmd = &cobra.Command{Use: "testCmd",Short: "A test cmd",Run: testCmdFunc,
}var testFlag1 stringfunc testCmdFunc(cmd *cobra.Command, args []string) {fmt.Println("test cmd function execute.")if len(args) > 0 {i := 0for 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")
}
  • 执行子命令 testCmd:
app testCmd -h 

可以看到输出如下:

A test cmdUsage: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")
  • 执行命令并输出标志参数:
app  testCmd arg1 -f global_flag -t local_flag

输出结果如下:

test cmd function execute.args[0]:arg1
local cmd flags: local_flag
root cmd flags: global_flag

本文链接:https://my.lmcjl.com/post/7566.html

展开阅读全文

4 评论

留下您的评论.