共计 2099 个字符,预计需要花费 6 分钟才能阅读完成。
应用 cobra-cli 搭建手脚架
# 装置 cobra-cli
go install github.com/spf13/cobra-cli@latest
# 创立一个利用
mkdir myapp && cd myapp
# 初始化 go mod
go mod init myapp
# 应用 cobra-cli 搭建手脚架
cobra-cli init
留神: cobra-cli 在 go1.18+ 的 go work 模式下有 bug, 不要应用 go work 模式
2022 年 11 月 18 日的最新版本 1.3.0 查看 issue https://github.com/spf13/cobra-cli/issues/26
查看生成的代码
$ tree -L 2
.
├── LICENSE
├── cmd
│ └── root.go
├── go.mod
├── go.sum
└── main.go
测试运行
$ 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.
新增命令
cobra-cli add serve
cobra-cli add config
查看新增的命令
$ 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.
Usage:
myapp [command]
Available Commands:
completion Generate the autocompletion script for the specified shell
config A brief description of your command
help Help about any command
serve A brief description of your command
Flags:
-h, --help help for myapp
-t, --toggle Help message for toggle
Use "myapp [command] --help" for more information about a command.
$
新增 config 命令的子命令
cobra-cli add create -p 'configCmd'
查看新增的子命令
$ go run main.go config --help
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:
myapp config [flags]
myapp config [command]
Available Commands:
create A brief description of your command
Flags:
-h, --help help for config
Use "myapp config [command] --help" for more information about a command.
$
填充业务逻辑
定义 Flags
Flag 有 2 种, Persistent Flag 和 Local Flag, Persistent Flag 能够在此命令和所有的子命令都失效, Local Flag 只是在此命令失效
比方绑定到 rootCmd 的 Persistent Flag 相当于全局 Flag, 所有的命令都能调用
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
然而 Local Flag 只是在以后无效
localCmd.Flags().StringVarP(&Source, "source", "s", "","Source directory to read from")
reference
更多参考
- https://github.com/spf13/cobra-cli
- https://github.com/spf13/cobra
本文由 mdnice 多平台公布
正文完