安装这里参数网上的方法 go get -v github.com/spf13/cobra/cobra
或者 gopm get -g github.com/spf13/cobra/cobra
用原生的go get方法安装可以获取一堆依赖, 比较慢, 安装没完成的时候, 再使用gopm安装, 无法更新了, 我是go get 一次性安装, 中间遇到安装不了的, 使用gopm补一下
安装后, gopath/bin目录下面会有 cobra.exe , 如果没有, 应该使用 go install package安装一下, 我也不记得有没有执行这一步, 我看到目录下面是有 cobra.exe的
下面开始参考网上的一个例子来试玩一下cobra如何使用
参考文章 https://blog.youkuaiyun.com/u010931295/article/details/82659025
进入 GOPATH src 目录下面 执行
cobra init demo --pkg-name demo
运行 go run main.go
运行成功,显示提示消息
添加子命令
cobra add test
在cmd目录生成新文件 test.go
运行命令 go run main.go test
此时编译 go build
然后生成 demo.exe
执行命令 demo.exe test 打印test命令的调用消息
下面来修改 test.go, 熟悉一下命令的使用
添加子命令的子命令
cobra add subtest
修改init的地方
func init() {
testCmd.AddCommand(subtestCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// subtestCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// subtestCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
测试 go run main.go test subtest
添加参数测试, 可以从shell传入参数, 两处修改
init的地方定义参数名, Run func获取参数
其中 user是长名, u是短名
使用方法如下
go run main.go test --user=test
go run main.go test --u=test
等号可以去掉
go run main.go test --user test
go run main.go test --u=test
go build后, 传入参数
.\demo.exe test -u testssss