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峰会上正式发布,社区里涌现了很多文章,我也计划写个系列文 ...
随机推荐
- BUCK电路和BL8033使用记录
我开始时用的是MPS的MP1584EN,这个芯片各方面都挺不错的.有次老大让我画个降压电路,看到用的是MP1584就说国外的芯片太贵,让我用上海贝岭的BL8033.BL8033确实很好用,虽然它没有1 ...
- eNSP路由器启动#号问题排查
1.删除拖出来的设备,重新拖出来一台---我用过[有时候好使] 2.确保Ensp的设置-工具-Virtual Box安装目录是否正确--我也遇到过[尤其是卸载掉Virtual Box重装之后] 3.确 ...
- 进阶实战 css 点击按钮的样式
1. html结构 <div class="menu-wrap"> <input type="checkbox" class="t ...
- Handler异步通信系统
handler是Android给我们提供用来更新UI的一套机制,也是一套消息处理机制,我们可以发消息,也可以通过它处理消息. Handler机制主要的几个角色:Handler,Message,Loop ...
- 【审视】Scrum Master的检查清单
一般情况下,一个Scrum Master如果更多的是做组织会议.确保时间盒以及对流程中的障碍快速响应等事项的话,可以同时引导2-3个团队.在这种情况下,团队会在降低问题发生率的基础上提高一定的绩效. ...
- XCTF练习题---MISC---stegano
XCTF练习题---MISC---stegano flag:flag{1nv151bl3m3554g3} 解题步骤: 1.观察题目,下载附件 2.打开发现是一张PDF图片,尝试转换word无果后,想到 ...
- 【MyBatis】多关键字的模糊查询
目录 情景分析 题目 要求 相关代码 Mapper.java Impl.java mapper.xml test.java 思路分析 1.最开始,参数没有使用List,引起的问题 2.Mybatis的 ...
- data structure assignment problem record
Question1: Similar to pause command in linux read -n 1 Question2 read : Illegal option -n 原因为ubuntu ...
- MySQL8新增降序索引
MySQL8新增降序索引 桃花坞里桃花庵,桃花庵里桃花仙.桃花仙人种桃树,又摘桃花卖酒钱. 一.MySQL5.7 降序索引 MySQL在语法上很早就已经支持降序索引,但实际上创建的却仍然是升序索引,如 ...
- leetcode 524. Longest Word in Dictionary through Deleting 通过删除字母匹配到字典里最长单词
一.题目大意 https://leetcode.cn/problems/longest-word-in-dictionary-through-deleting 给你一个字符串 s 和一个字符串数组 d ...