1.cobra简介
Cobra既是用于创建强大的现代CLI应用程序的库,也是用于生成应用程序和命令文件的程序。
Cobra在golang项目中的应用十分的广泛,有很多成名的工具都使用到了cobra
例如kubernetes(k8s)、docker、Hugo等,如果需要了解这些go开源项目的源码的话,Cobra是必须要学习的。
2.cobra功能
- 拥有简易的子命令行模式,如 app server, app fetch等,十分的便捷
- 完全的兼容posix等命令行的模式
- 可以使用嵌套子命令
- 完全支持flags
- 使用Cobra很容易的生成应用程序和命令,使用cobra create appname和cobra add cmdname
- 如果命令输入错误,将提供智能建议,如 app srver,将提示srver没有,是否是app server
- 自动生成commands和flags的帮助信息
- 自动生成详细的help信息,如app help
- 自动识别-h,--help帮助flag
- 自动生成应用程序在bash下命令自动完成功能
- 自动生成应用程序的man手册
- 命令行别名
- 自定义help和usage信息
3.linux下cobra安装
-
使用go mod模式
go env -w GO111MODULE=on
-
下载cobra安装包和二进制文件cobra-cli,通过cobra-cli可以快速创建出一个cobra基础的代码结构。
go get -u github.com/spf13/cobra@latest go install github.com/spf13/cobra-cli@latest 如果有报错: go get github.com/spf13/cobra@latest: module github.com/spf13/cobra: Get "https://proxy.golang.org/github.com/spf13/cobra/@v/list": dial tcp xx:443: i/o timeout 解决方法: go env -w GOPROXY=https://goproxy.cn
4.使用go mod init初始化项目
[xt@zl cobra]$ go mod init cobra
go: creating new go.mod: module cobra
-rw-rw-r-- 1 xt xt 19 Jul 25 14:33 go.mod
使用cobra-cli init初始化代码示例
[xt@zl cobra]$ cobra-cli init
total 4004
drwxrwxrwx 2 xt xt 21 Jul 25 14:21 cmd
-rwxrwxrwx 1 xt xt 4086123 Jul 25 14:21 cobra
-rwxrwxrwx 1 xt xt 178 Jul 25 14:18 go.mod
-rwxrwxrwx 1 xt xt 896 Jul 25 14:18 go.sum
-rwxrwxrwx 1 xt xt 0 Jul 25 14:20 LICENSE
-rwxrwxrwx 1 xt xt 116 Jul 25 14:20 main.go
目录结构
[xt@zl cobra]$ tree .
.
├── cmd
│ └── root.go
├── cobra
├── go.mod
├── go.sum
├── LICENSE
└── main.go
1 directory, 6 files
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: `this is a long message`,
// 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")
}
编译main.go文件
[xt@zl cobra]$ go build
执行二进制文件cobra
[xt@zl cobra]$ ./cobra
this is a long message
本文正在参加技术专题18期-聊聊Go语言框架 \