go Cobra命令行工具入门
简介

为什么需要cobra
使用前
package main import (
"flag"
"fmt"
) func main() {
flag.Parse() args := flag.Args()
if len(args) <= 0 {
fmt.Println("Usage: admin-cli [command]")
return
} switch args[0] {
case "help":
// ...
case "export":
//...
if len(args) == 3 { // 导出到文件
// todo
} else if len(args) == 2 { // 导出...
// todo
}
default:
//...
}
}
使用后
package main import (
"fmt"
"github.com/spf13/cobra"
"os"
) // rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "api",
Short: "A brief description of your application",
Long: `A longer description `,
} // 命令一
var mockMsgCmd = &cobra.Command{
Use: "mockMsg",
Short: "批量发送测试文本消息",
Long: ``,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("mockMsg called")
},
} // 命令二
var exportCmd = &cobra.Command{
Use: "export",
Short: "导出数据",
Long: ``,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("export called")
},
} func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
} func init() {
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") rootCmd.AddCommand(mockMsgCmd)
rootCmd.AddCommand(exportCmd) exportCmd.Flags().StringP("out", "k", "./backup", "导出路径")
} func main() {
Execute()
}
$ go run main.go
A longer description Usage:
api [command] Available Commands:
completion Generate the autocompletion script for the specified shell
export 导出数据
help Help about any command
mockMsg 批量发送测试文本消息 Flags:
-h, --help help for api
-t, --toggle Help message for toggle Use "api [command] --help" for more information about a command.
基本概念
- 命令(Commands ):代表行为。命令是程序的中心点,程序的每个功能都应该可以通过命令进行交互,一个命令可以有任意个子命令。
- 参数(Args):命令的参数
- 标志(Flags):修饰命令。它修饰命令该如何完成。
$ ./appName command args --Flag
- appName: hugo
- command: server
- flag: port
安装
Go pkg
$ go get -u github.com/spf13/cobra@latest
import "github.com/spf13/cobra"
命令行工具
# 命令行工具
$ go install github.com/spf13/cobra-cli@latest
$ cobra-cli --help
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:
cobra-cli [command] Available Commands:
add Add a command to a Cobra Application
completion Generate the autocompletion script for the specified shell
help Help about any command
init Initialize a Cobra Application Flags:
-a, --author string author name for copyright attribution (default "YOUR NAME")
--config string config file (default is $HOME/.cobra.yaml)
-h, --help help for cobra-cli
-l, --license string name of license for the project
--viper use Viper for configuration Use "cobra-cli [command] --help" for more information about a command.
入门实践
新建cobra命令行程序
$ cobra-cli init
├── LICENSE
├── cmd
│ └── root.go
└── main.go
package main import "tools/api/cmd" func main() {
cmd.Execute()
}
root.go(有删减):
package cmd import (
"fmt" "github.com/spf13/cobra"
) // rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "api",
Short: "A brief description of your application",
Long: `A longer description `,
//Run: func(cmd *cobra.Command, args []string) {
// fmt.Println("api called")
//},
} // Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
} func init() {
// 全局flag
// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.api.yaml)") // local flag,暂不知道用处
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
$ go build
$ ./api
A longer description Usage:
api [command] Available Commands:
completion Generate the autocompletion script for the specified shell
help Help about any command Flags:
-h, --help help for api
-t, --toggle Help message for toggle Use "api [command] --help" for more information about a command.
命令构成
- Available Commands:代表可以执行的命令。比如./api connect
- Flags:是参数。比如./api connect --ip=127.0.0.1:6379,--ip就是flag,127.0.0.1:6379就是flag的值。
新增命令
$ cobra-cli add [command]
$ cobra-cli add mock-msg
mockMsg created at /Users/xxx/repo/tools/api
package cmd import (
"fmt" "github.com/spf13/cobra"
) var mockMsgCmd = &cobra.Command{
Use: "mockMsg",
Short: "A brief description of your command",
Long: `mock msg command`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("mockMsg called")
},
} func init() {
rootCmd.AddCommand(mockMsgCmd)
}
$ go build
$ ./api
// ...
Available Commands:
completion Generate the autocompletion script for the specified shell
help Help about any command
mockMsg A brief description of your command
// ...
$ ./api mockMsg mockMsg called
如何显示自己的命令用法
./api mockMsg help
批量生产mq消息 Usage:
benchmark mockmsg [flags] Flags:
-g, --goroutine int32 并发routine数量 (default 1)
-h, --help help for mockmsg
-p, --packet int32 每个routine一秒写入mq的数量 (default 20)
-g和-p是新增的2个flag:
func init() {
mockmsgCmd.Flags().Int32P("goroutine", "g", 1, "并发routine数量")
mockmsgCmd.Flags().Int32P("packet", "p", 20, "每个routine一秒写入mq的数量") rootCmd.AddCommand(mockmsgCmd)
}
// mockmsgCmd represents the mockmsg command
var mockmsgCmd = &cobra.Command{
Use: "mockmsg",
Short: "批量生产mq消息",
Run: func(cmd *cobra.Command, args []string) {
// 这里要写全名
g, _ := cmd.Flags().GetInt32("goroutine")
p, _ := cmd.Flags().GetInt32("packet")
fmt.Println("mockmsg called,flags:g=", g, ",p=", p, ",args:", args)
},
}
$ go run main.go mockmsg -p 322 -g 5 args1 args2
mockmsg called,flags:g= 5 ,p= 322 ,args: [args1 args2]
总结
- https://blog.csdn.net/qq_31639829/article/details/118889580
- https://github.com/mattermost/mattermost-server
go Cobra命令行工具入门的更多相关文章
- 探索Windows命令行系列(2):命令行工具入门
1.理论基础 1.1.命令行的前世今生 1.2.命令执行规则 1.3.使用命令历史 2.使用入门 2.1.启动和关闭命令行 2.2.执行简单的命令 2.3.命令行执行程序使用技巧 3.总结 1.理论基 ...
- [易学易懂系列|rustlang语言|零基础|快速入门|(25)|实战2:命令行工具minigrep(2)]
[易学易懂系列|rustlang语言|零基础|快速入门|(25)|实战2:命令行工具minigrep(2)] 项目实战 实战2:命令行工具minigrep 我们继续开发我们的minigrep. 我们现 ...
- [易学易懂系列|rustlang语言|零基础|快速入门|(24)|实战2:命令行工具minigrep(1)]
[易学易懂系列|rustlang语言|零基础|快速入门|(24)|实战2:命令行工具minigrep(1)] 项目实战 实战2:命令行工具minigrep 有了昨天的基础,我们今天来开始另一个稍微有点 ...
- 《Java从入门到失业》第二章:Java环境(三):Java命令行工具
2.3Java命令行工具 2.3.1编译运行 到了这里,是不是开始膨胀了,想写一段代码来秀一下?好吧,满足你!国际惯例,我们写一段HelloWorld.我们在某个目录下记事本,编写一段代码如下: 保存 ...
- .NET Core系列 : 1、.NET Core 环境搭建和命令行CLI入门
2016年6月27日.NET Core & ASP.NET Core 1.0在Redhat峰会上正式发布,社区里涌现了很多文章,我也计划写个系列文章,原因是.NET Core的入门门槛相当高, ...
- **代码审查:Phabricator命令行工具Arcanist的基本用法
Phabricator入门手册 http://www.oschina.net/question/191440_125562 Pharicator是FB的代码审查工具,现在我所在的团队也使用它来进行代码 ...
- 【No.2】监控Linux性能25个命令行工具
接着上一篇博文继续 [No.1]监控Linux性能25个命令行工具 10:mpstat -- 显示每个CPU的占用情况 该命令可以显示每个CPU的占用情况,如果有一个CPU占用率特别高,那么有可能是一 ...
- 【No.1】监控Linux性能25个命令行工具
如果你的Linux服务器突然负载暴增,告警短信快发爆你的手机,如何在最短时间内找出Linux性能问题所在?通过以下命令或者工具可以快速定位 top vmstat lsof tcpdump netsta ...
- NET Core 环境搭建和命令行CLI入门
NET Core 环境搭建和命令行CLI入门 2016年6月27日.NET Core & ASP.NET Core 1.0在Redhat峰会上正式发布,社区里涌现了很多文章,我也计划写个系列文 ...
随机推荐
- 移动安卓App+BurpSuite的渗透测试
从Android 7.0及以上版本开始,安卓系统更改了信任用户安装证书的默认行为,用户安装的证书都是用户证书,因此不管是filddle还是burp,都是把他们的根证书安装到了用户证书,而有部分移动ap ...
- 轻量迅捷时代,Vite 与Webpack 谁赢谁输
你知道Vite和Webpack吗?也许有不少"程序猿"对它们十分熟悉. Webpack Webpack是一个JavaScript应用程序的静态模块打包工具,它会对整个应用程序进行依 ...
- js 修改页面样式的两种方式
1. element.style 行内样式操作 代码示例 : <!DOCTYPE html> <html lang="en"> <hea ...
- 百度飞桨数据处理 API 数据格式 HWC CHW 和 PIL 图像处理之间的关系
使用百度飞桨 API 例如:Resize Normalize,处理数据的时候. Resize:如果输入的图像是 PIL 读取的图像这个数据格式是 HWC ,Resize 就需要 HWC 格式的数据. ...
- 前端优化建议:合理利用JavaScript的条件运算符
在最近的项目中要使用到一个格式化文件大小的算法,于是不假思索写了如下代码: function formatSize(size){ if(size<1024){ return size+" ...
- Python实现双X轴双Y轴绘图
诈尸人口回归.这一年忙着灌水忙到头都掉了,最近在女朋友的提醒下终于想起来博客的账号密码,正好今天灌水的时候需要画一个双X轴双Y轴的图,研究了两小时终于用Py实现了.找资料的过程中没有发现有系统的文章, ...
- Python打印表格
使用Python在终端打印表格 import prettytable table = PrettyTable(['Title1', 'Title2', 'Title3']) table.add_row ...
- VUE 日期组件(包括年选择)
封装vant 日期组件实现可以选择年份 <template> <div class="yearMonMain"> <div class="l ...
- Linux 服务器的性能参数指标总结
关注「开源Linux」,选择"设为星标" 回复「学习」,有我为您特别筛选的学习资料~ 前言 一个基于 Linux 操作系统的服务器运行的同时,也会表征出各种各样参数信息.通常来说运 ...
- Kubernetes 的这些原理,你一定要了解
点击上方"开源Linux",选择"设为星标" 回复"学习"获取独家整理的学习资料! 作者:fredalxin地址:https://freda ...