简介

Star:26.5K
 
Cobra是一个用Go语言实现的命令行工具。并且现在正在被很多项目使用,例如:Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速的创建命令行工具,特别适合写测试脚本,各种服务的Admin CLI等。
 
比如 Mattermost 项目,就写了很多 Admin CLI:
 

为什么需要cobra

我们看一个简单的demo

使用前

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.

  

发现了吗?你不用再处理各种参数组合了,从此释放了出来,只需要写自己的业务逻辑即可!

基本概念

Cobra由三部分组成:
  • 命令(Commands ):代表行为。命令是程序的中心点,程序的每个功能都应该可以通过命令进行交互,一个命令可以有任意个子命令。
  • 参数(Args):命令的参数
  • 标志(Flags):修饰命令。它修饰命令该如何完成。
官方推荐命令格式为:
$ ./appName command args --Flag  
 
如 hugo server --port=1313 :
  • appName: hugo
  • command: server
  • flag: port

安装

Go pkg

添加依赖
$ go get -u github.com/spf13/cobra@latest

  

导入即可:
import "github.com/spf13/cobra"  

命令行工具

建议安装命令行工具 `cobra-cli` ,以方便快速创建cobra项目,增加command等。

# 命令行工具
$ go install github.com/spf13/cobra-cli@latest

  

安装完成之后,执行 `cobra-cli --help` (请确保GOBIN已配置),输出下列信息则代表成功:
$ 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 初始化创建项目:
$ cobra-cli init

  

此时,在当前目录自动生成如下文件:
├── LICENSE
├── cmd
│ └── root.go
└── main.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")
}

 

此时运行,不用指定参数,会执行rootCmd,打印使用说明:
$ 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

  

此时,在cmd下会多一个文件(mock_msg.go),内容如下:
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)
}

  

再执行rootCmd:
$ 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
// ...

  

执行mocMsg命令:
$ ./api mockMsg

mockMsg called

  

此时,就可以在生成的 mock_msg.go: Run() 函数中,放你自己的业务逻辑代码了。

如何显示自己的命令用法

上面新增了一个命令mockMsg,通过 ./api help 打印了命令和help,但是 `Use` 里面指定的内容打印到哪里去了呢?
 
这个时候,需要针对Command在指定help,此时就能打印这个命令的具体用法了。
./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)
}

  

获取这2个值:
// 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]

总结

我们通过一个例子,介绍了使用cobra带来的好处。通过一个完整的入门实践,演示了创建项目、添加命令和使用的一些示例,希望对你有所帮助!
 
参考:

go Cobra命令行工具入门的更多相关文章

  1. 探索Windows命令行系列(2):命令行工具入门

    1.理论基础 1.1.命令行的前世今生 1.2.命令执行规则 1.3.使用命令历史 2.使用入门 2.1.启动和关闭命令行 2.2.执行简单的命令 2.3.命令行执行程序使用技巧 3.总结 1.理论基 ...

  2. [易学易懂系列|rustlang语言|零基础|快速入门|(25)|实战2:命令行工具minigrep(2)]

    [易学易懂系列|rustlang语言|零基础|快速入门|(25)|实战2:命令行工具minigrep(2)] 项目实战 实战2:命令行工具minigrep 我们继续开发我们的minigrep. 我们现 ...

  3. [易学易懂系列|rustlang语言|零基础|快速入门|(24)|实战2:命令行工具minigrep(1)]

    [易学易懂系列|rustlang语言|零基础|快速入门|(24)|实战2:命令行工具minigrep(1)] 项目实战 实战2:命令行工具minigrep 有了昨天的基础,我们今天来开始另一个稍微有点 ...

  4. 《Java从入门到失业》第二章:Java环境(三):Java命令行工具

    2.3Java命令行工具 2.3.1编译运行 到了这里,是不是开始膨胀了,想写一段代码来秀一下?好吧,满足你!国际惯例,我们写一段HelloWorld.我们在某个目录下记事本,编写一段代码如下: 保存 ...

  5. .NET Core系列 : 1、.NET Core 环境搭建和命令行CLI入门

    2016年6月27日.NET Core & ASP.NET Core 1.0在Redhat峰会上正式发布,社区里涌现了很多文章,我也计划写个系列文章,原因是.NET Core的入门门槛相当高, ...

  6. **代码审查:Phabricator命令行工具Arcanist的基本用法

    Phabricator入门手册 http://www.oschina.net/question/191440_125562 Pharicator是FB的代码审查工具,现在我所在的团队也使用它来进行代码 ...

  7. 【No.2】监控Linux性能25个命令行工具

    接着上一篇博文继续 [No.1]监控Linux性能25个命令行工具 10:mpstat -- 显示每个CPU的占用情况 该命令可以显示每个CPU的占用情况,如果有一个CPU占用率特别高,那么有可能是一 ...

  8. 【No.1】监控Linux性能25个命令行工具

    如果你的Linux服务器突然负载暴增,告警短信快发爆你的手机,如何在最短时间内找出Linux性能问题所在?通过以下命令或者工具可以快速定位 top vmstat lsof tcpdump netsta ...

  9. NET Core 环境搭建和命令行CLI入门

    NET Core 环境搭建和命令行CLI入门 2016年6月27日.NET Core & ASP.NET Core 1.0在Redhat峰会上正式发布,社区里涌现了很多文章,我也计划写个系列文 ...

随机推荐

  1. @RequestBody和@RequestParam注解以及返回值,ajax相关知识点

    关于前后端传递json数据这块查了好多资料,好多地方还是不清楚,先记录一下清楚的地方. 如果我们前端使用ajax发json数据,一般都加上contentType:'application/json;c ...

  2. python中的嵌套

    嵌套:将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套.既可以在列表中嵌套字典,也可以在字典中嵌套列表,甚至在字典中嵌套字典. 一.列表中嵌套字典 1)一般创建方式: student_ ...

  3. 2021.12.02 P4001 [ICPC-Beijing 2006]狼抓兔子(最小割)

    2021.12.02 P4001 [ICPC-Beijing 2006]狼抓兔子(最小割) https://www.luogu.com.cn/problem/P4001 题意: 把图分成两部分需要的最 ...

  4. python黑帽子(第四章)

    Scapy窃取ftp登录账号密码 sniff函数的参数 filter 过滤规则,默认是嗅探所有数据包,具体过滤规则与wireshark相同. iface 参数设置嗅探器索要嗅探的网卡,默认对所有的网卡 ...

  5. 微服务状态之python巡查脚本开发

    背景 由于后端微服务架构,于是各种业务被拆分为多个服务,服务之间的调用采用RPC接口,而Nacos作为注册中心,可以监听多个服务的状态,比如某个服务是否down掉了.某个服务的访问地址是否改变.以及流 ...

  6. 数据结构 - AVL 树

    简介 基本概念 AVL 树是最早被发明的自平衡的二叉查找树,在 AVL 树中,任意结点的两个子树的高度最大差别为 1,所以它也被称为高度平衡树,其本质仍然是一颗二叉查找树. 结合二叉查找树,AVL 树 ...

  7. 【在下版本,有何贵干?】Dockerfile中 RUN yum -y install vim失败Cannot prepare internal mirrorlist: No URLs in mirrorlist

    隐秘的版本问题---- Dockerfile中 RUN yum -y install vim失败Cannot prepare internal mirrorlist: No URLs in mirro ...

  8. MySQL性能优化 - 别再只会说加索引了

    MySQL性能优化 MySQL性能优化我们可以从以下四个维度考虑:硬件升级.系统配置.表结构设计.SQL语句和索引. 从成本上来说:硬件升级>系统配置>表结构设计>SQL语句及索引, ...

  9. .NET混合开发解决方案11 WebView2加载的网页中JS调用C#方法

    系列目录     [已更新最新开发文章,点击查看详细] WebView2控件应用详解系列博客 .NET桌面程序集成Web网页开发的十种解决方案 .NET混合开发解决方案1 WebView2简介 .NE ...

  10. 第一个Python程序 | 机选彩票号码+爬取最新开奖号码

    (机选彩票号码+爬取最新开奖号码 | 2021-04-21) 学习记录,好记不如烂笔头 这个程序作用是<机选三种彩票类型的号码> 程序内包含功能有如下: 自动获取最新的三种彩票的开奖号码 ...