Cobra
在命令行的程序中,是服务端最经常使用的,因为他方便,而且效率高。为了提高命令行程序的开发速度,golang
中有一个框架是Cobra
。
我们一起来看看Cobra
是怎么简化我们开发控制行命令的。
github 的地址在这里。
Cobra 的安装
Cobra
使用的人特别的多,github
的很多工具都是用Cobra
开发的,看了下文档,用起来确实非常的简单。
安装非常的简单:
go install github.com/spf13/cobra-cli@latest
这时候我们就可以使用cobra-cli
命令了。
D:\work\GolangProjects>cobra-cli
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:
cobra-cli [command]
Available Commands:
add Add a command to a Cobra Application
completion Generate the autocompletion script for the specified shell
help Help about any command
init Initialize a Cobra Application
Flags:
-a, --author string author name for copyright attribution (default "YOUR NAME")
--config string config file (default is $HOME/.cobra.yaml)
-h, --help help for cobra-cli
-l, --license string name of license for the project
--viper use Viper for configuration
Use "cobra-cli [command] --help" for more information about a command.
实例
还是从helloworld
上开始,用框架创建helloworld
应用:
#创建目录
mkdir helloapp
cd helloapp
#创建mod文件
go mod init helloapp
#初始化
cobra-cli init
初始化完了以后,他就帮我们生成了如下的文件:
│ go.mod
│ go.sum
│ LICENSE
│ main.go
│
└─cmd
root.go
运行命令,看看输出:
D:\work\GolangProjects\helloapp>go run main.go
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.
打开 root.go
就可以看到这一句话。
添加我们的命令:
D:\work\GolangProjects\helloapp>cobra-cli add hello
hello created at D:\work\GolangProjects\helloapp
运行下:
D:\work\GolangProjects\helloapp>go run main.go
出现
hello call
这就是我们使用框架的好处,很容易就构建一个命令参数。
添加如下的代码:
func inHello(args []string) {
helloto := ""
for _, ival := range args {
helloto = helloto + ival
}
fmt.Printf("Welcome to app, %s \n", helloto )
}
helloCmd
变为如下:
// helloCmd represents the hello command
var helloCmd = &cobra.Command{
Use: "hello",
Short: "A brief description of your command",
Long: `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.`,
Run: func(cmd *cobra.Command, args []string) {
inHello(args)
},
}
运行:
D:\work\GolangProjects\helloapp>go run main.go hello pp io
Welcome to app, ppio
我们获取了各个参数,组合起来做事情。
这个就是Cobra
的使用。