首页 > 技术文章 > cobra:生成解析命令行参数工具

pxlsdz 2022-01-24 22:40 原文

cobra:生成解析命令行参数工具

简介

cobrago 语言的一个命令行程序库,可以用于编写命令行工具。非常多知名的开源项目使用了 cobra 库构建命令行,如KubernetesHugoetcd等等

安装

Cobra 非常易用,首先使用 go get 命令安装最新版本。

go get -u github.com/spf13/cobra/cobra

直接使用需要将Cobra ,需要将$GOBIN加入到环境变量(百度一下方法)去, go env查看`GOBIN代表的路径值。

image-20220124211233629

从截图上可以看到,输出的结果中主要包括三部分:UsageAvailable CommandsFlags。其中 Usage 是告诉你该命令总的用法, Available Commands 告诉你有哪些子命令,Flags 则是告诉你可以用哪些参数。

总的来说,一个优秀的程序命令由三部分组成:主命令、子命令、参数。主命令是整个程序的入口,子命令是程序内各种主要的功能,参数则是告诉程序如何执行这些功能。

何使用 cobra 命令生成代码呢?

以秒杀服务为例子,主命令应该是seckill。秒杀服务包括秒杀接口服务和秒杀管理后台后端,它们的子命令分别是apiadmin。另外,为了方便做一些比较复杂的压力测试,我们还可以提供一个bench命令。

使用 cobra 命令生成代码

cobra init [seckill,可不写]
cobra add api
cobra add admin
cobra add bench

我们就获得了 cmd/root.gocmd/api.gocmd/admin.gocmd/bench.go。他们分别是主命令 seckill、子命令 apiadminbench 的入口文件。

打开 cmd/root.go,你将看到如下两段代码:

/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>

*/
package cmd

import (
	"os"

	"github.com/spf13/cobra"
)



// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "cobra",
	Short: "A brief description of your application",
	Long: `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.`,
	// Uncomment the following line if your bare application
	// has an action associated with it:
	// Run: func(cmd *cobra.Command, args []string) { },
}

// 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() {
	// Here you will define your flags and configuration settings.
	// Cobra supports persistent flags, which, if defined here,
	// will be global for your application.

	// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")

	// Cobra also supports local flags, which will only run
	// when this action is called directly.
	rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}



其中 rootCmd 是主命令的配置,类型是 \*cobra.Command。它的 Use 字段是主命令名称,Short 字段是对命令的简短描述,Long 字段是对命令的详细描述。Short 字段和 Long 字段目前还是默认值,需要修改成秒杀命令的描述。

需要注意的是,rootCmd 中的 Run 字段默认是被注释掉的。该字段是 cobra 解析完命令行参数后正式执行功能的入口函数,你可以开启它,并在其中根据参数做一些初始化的工作。

init 函数中,cobra 会执行配置的初始化,并解析命令行参数。在生成的代码中,已经提供了 config 参数,用于指定配置文件路径。通常,命令行参数有长参数和短参数这两种格式,这里的 config 是长参数,在使用的时候是 --config 这种形式,而后面的 c 是短参数,使用的时候是 -c 这种形式。

cmd 目录下的 api.goadmin.gobench.go 也类似,区别在于各子命令的 cmd 配置中 Run 字段是有个默认函数的。并且,在 init 函数中,会有类似 rootCmd.AddCommand(adminCmd) 的代码将子命令的配置添加到主命令的配置中。

编译代码,执行 ./seckill help 命令便可以看到 seckill 的帮助信息。如下所示:

go build -o seckill main.go

image-20220124223516223

推荐阅读