当前位置:网站首页>golang CLI框架--cobra
golang CLI框架--cobra
2022-06-10 10:27:00 【oneslide】
https://github.com/spf13/cobra.git
使用golang可以很方便把代码编译成二进制,但是如何写出类似linux工具那样,符合posix标准的工具呢?答案是cobra。
kubectl使用cobra框架实现。
快速开始
使用cobra-cli脚手架快速创建项目
go install github.com/spf13/[email protected]
cobra-cli应该安装到$GOPATH/bin目录下,确保$GOPATH/bin在PATH目录下
运行下面命令快速初始化:
cobra-cli init
会生成如下结构:
- main.go
+ cmd
- root.go
此时就已经可以运行项目简单的试试效果:
$ go run main.go -h
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.
Usage:
cobra-test [flags]
cobra-test [command]
Available Commands:
completion Generate the autocompletion script for the specified shell
help Help about any command
Flags:
-h, --help help for cobra-test
-t, --toggle Help message for toggle
添加一个子命令
比如:
git clone xxx
其中clone即是一个子命令,如何添加一个类似的?
运行下面命令,即会生成一个serve.go
cobra-cli add serve
添加开关参数
- serve.go
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
// serveCmd represents the serve command
var serveCmd = &cobra.Command{
Use: "serve",
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("serve called")
// 位置参数
fmt.Println(args)
// 开关参数
fmt.Println(cmd.Flags().GetBool("toggle"))
},
}
func init() {
rootCmd.AddCommand(serveCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// serveCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
serveCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
args代表位置参数,toggle代表开关参数
$ go run main.go serve -t hello
serve called
[hello]
true <nil>
长参数
git clone --config /etc/config.yaml
其中--config /etc/config.yaml这种是符合POSIX标准的长参数。
package cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
// config file path
var cfgFile string
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "cobra-test",
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) {
// 这里根据参数获取情况,执行相关逻辑
fmt.Println(cfgFile)
},
}
// 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-test.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")
// 这一行定义类似 go run main.go --config xxx.yaml
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
}
边栏推荐
猜你喜欢

今天19:30 | 图形学专场——中国科学院计算技术研究所高林老师团队

「诗经」主题文化数字藏品中奖名单公布

2023王道C语言训练营(二叉查找树-顺序查找-折半查找)

"Bookofsongs" themed cultural digital collection winners announced

基于SSH的音乐检索系统

MySQL的体系结构

学术讲座: 多标签主动学习之 MASP

Conversion between binary, octal, decimal and hexadecimal (integer plus decimal)

“大写意花鸟画宗师李苦禅先生”重磅数字藏品全网首发

Eg2131 test circuit
随机推荐
【高并发】关于乐观锁和悲观锁,蚂蚁金服面试官问了我这几个问题!!
单片机触发器或非门工作原理以及用途
「诗经」主题文化数字藏品中奖名单公布
[first hpm6750 evaluation] RT thread development environment construction and hello world
Dr. jiangxiaowei, a member of hpca Hall of fame, is the chief scientist of Dayu smart core
效率工具 : uTools
Conversion between binary, octal, decimal and hexadecimal (integer plus decimal)
渡远户外冲刺深交所:年营收3.5亿 林锡臻家族色彩明显
2023 Wangdao C language training camp (clue binary tree)
Implementation code of several recent good papers (with source code download)
Leetcode 2000. Reverse word prefix
可以在网上炒股开户吗?是安全的吗?
Eg2131 test circuit
Print: Entry, ':CFBundleIdentifier', Does Not Exist
Detailed steps for installing mysql+django under mac
[interesting reading] deepinf: social influence prediction with deep learning
Question bank and answers of 2022 metal and nonmetal mine hoist operation examination
【先楫HPM6750测评】RT-Thread开发环境搭建和Hello World
高考志愿填报,城市、学校与专业怎么选?
数组目标值target两个整数,并返回它们的数组下标