一、介绍
cobra库是go最常用的命令行库。
开原地址:https://github.com/spf13/cobra
二、快速使用
1、新建目录
mkdir cobratest && cd cobratest
2、初始化go mod
go mod init sample/cobratest
此时我们打开go.mod 第一行写了我们的包名为 sample/cobratest
module sample/cobratest
go 1.14
require (
github.com/inconshreveable/mousetrap v1.0.1 // indirect
github.com/spf13/cobra v1.5.0 // indirect
)
3、安装cobra
go get -u github.com/spf13/cobra@latest
4、cobra初始化
cobra init --pkg-name sample/cobratest
我们打开命令行使用tree命令看一下文件目录
➜ cobratest git:(master) ✗ tree
.
├── LICENSE
├── cmd
│ └── root.go
├── go.mod
├── go.sum
└── main.go
1 directory, 5 files
5、新建一个子命令 cronMyFirst
cobra add cronMyFirst
我们会发现在 cmd目录同级root.go 生成了一个新的文件 cronMyFirst.go
打开 cronMyFirst.go文件
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
// cronMyFirstCmd represents the cronMyFirst command
var cronMyFirstCmd = &cobra.Command{
Use: "cronMyFirst",
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) {
fmt.Println("cronMyFirst called")
},
}
func init() {
rootCmd.AddCommand(cronMyFirstCmd)
}
上面有一个 Use: "cronMyFirst", 也就是我们使用的时候 只要执行 cronMyFirst就行了。
6、使用一下 cronMyFirst
go run ./main.go cronMyFirst
输出:
cronMyFirst called
使用成功,当然我们也可以编译后再使用,如下:
go build -o cobratest ./main.go
./cobratest cronMyFirst
输出如下:
cronMyFirst called
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。