Go+Cobra快速入门
Cobra介绍
- 一个用于生成命令行工具的框架(本身也是个命令行工具)
- 非常简单,易用
- k8s/docker/hugo/etcd等...
下载安装
https://github.com/spf13/cobra
$ go get -u github.com/spf13/cobra
// github.com/spf13/cobra/cobra/main.go 编译后可以放到 GOPTH/bin/ 就可以直接使用了
// 在程序项目中引用 import "github.com/spf13/cobra"
初始化项目
/*
Usage:
cobra init [name] [flags]
Aliases:
init, initialize, initialise, create
Flags:
-h, --help help for init
--pkg-name string fully qualified pkg name
Global Flags:
-a, --author string author name for copyright attribution (default "YOUR NAME")
--config string config file (default is $HOME/.cobra.yaml)
-l, --license string name of license for the project
--viper use Viper for configuration (default true)
*/
// cobra 是github.com/spf13/cobra/cobra/main.go 编译后的可执行文件
// 基本初始化
cobra init --pkg-name xxx
// 修改作者信息
cobra init --pkg-name xxx --author xxx2
// 指定license信息
cobra init --pkg-name xxx -license xxx
命令的基本结构
var rootCmd = &cobra.Command{
Use: "clid",
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) { },
// Alias:[]string,
}
func init() {
rootCmd.AddCommand(versionCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// versionCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// versionCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
// Use: 与短简介对应显示 在启动时显示
// Short: 简介,在命令行后会跟一个短的备注
// Long: 一个长的帮助信息,会在执行-h帮助的时候显示
// run: func(cmd *cobra.Command, args []string) cmd是获取创建的对象指针可以获取信息比如选项 cmd.Flags().Get数据类型("参数名称"),args 获取没有捕获的参数并以切片返回 与 os.Args类似 ->执行对应use命令会执行对应的run函数
// 在 init 函数中 rootCmd.AddCommand(versionCmd) rootCmd可以替换其他子命令生成的 cobra.Command 对象 实现嵌套关系
编译与运行
与Go程序编译运行一致,无特殊需求
为命令添加一个子命令
cobra add xxx // xxx是子命令
// 创建完成后会在cmd目录下生成一个xxx.go的文件
为命令添加一个选项
func init() {
rootCmd.AddCommand(versionCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// versionCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// 添加参数
// versionCmd.Flags().数据类型P("参数名称","短的名称",默认值,"提示信息")
// 参数名称一般是 --参数名称
// 短的选项一般是 -短的名称
// 已经添加的参数在 run 函数中
versionCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
选项的接受和处理
// versionCmd represents the version command
var versionCmd = &cobra.Command{
Use: "version",
Short: "A brief description of your command",
Long: `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.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("version called")
// 获取参数
v, err := cmd.Flags().GetString("toggle")
if err != nil {
fmt.Println(err)
return
}
fmt.Println("v", v)
},
}
修改默认选项
// 如果需要修改初始化的help选项 cobra/command.go
// 1.全部更改
// func (c *Command) InitDefaultHelpCmd()
// 2.部分修改
// func (c *Command) SetHelpFunc(f func(*Command, []string))/(c *Command) SetHelpCommand(cmd *Command)/(c *Command) SetHelpTemplate(s string)
Songzhibin
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
2019-11-14 Promise解决回调地狱(多层调用问题)
2019-11-14 JavaScript动画相关