使用 cobra-cli 搭建手腳架
# 安裝 cobra-cli
go install github.com/spf13/cobra-cli@latest
# 創(chuàng)建一個(gè)應(yīng)用
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
測(cè)試運(yùn)行
$ 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.
$
填充業(yè)務(wù)邏輯
定義 Flags
Flag 有 2 種, Persistent Flag 和 Local Flag, Persistent Flag 可以在此命令和所有的子命令都生效, Local Flag 只是在此命令生效
比如綁定到 rootCmd 的 Persistent Flag 相當(dāng)于全局 Flag, 所有的命令都能調(diào)用
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
但是 Local Flag 只是在當(dāng)前有效
localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
reference
更多參考
本文由mdnice多平臺(tái)發(fā)布