Go 使用 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.
$
填充业务逻辑
定义 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
更多参考
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix