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

2020-01-28 13:06:26于丽

到此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:


srcdemo>....bincobra add test
test created at C:Usersliubo5Desktoptranscoding_toolsrcdemocmdtest.go

在src目录下demo的文件夹下生成了一个cmdtest.go文件,如下:

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

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


srcdemo>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,又能使用子命令


srcdemo>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命令输出信息,这里没有对默认信息进行修改。


srcdemo>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详细研究一下。这里只是一个简单的使用入门介绍,如果有错误之处,敬请指出,谢谢~

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易采站长站的支持。