使用 cobra-cli 搭建手脚架

使用 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.
$

填充业务逻辑

alt

定义 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

更多参考

本文由 mdnice 多平台发布

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JarvanStack

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值