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

填充业务逻辑

image.png

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

更多参考