【34】cobra 框架

一. cobra是什么

cobra是一个命令行程序库,可以用来编写命令行程序。同时,它也提供了一个脚手架,用于生成基于 cobra 的应用程序框架。非常多知名的开源项目使用了 cobra 库构建命令行,如Kubernetes、Hugo、etcd等等等等。

二. 引入cobra库

bash 复制代码
go get -u github.com/spf13/cobra

三. go示例代码

Go 复制代码
package main

import (
	"fmt"
	"github.com/spf13/cobra"
	"os"
	"strings"
)

var (
	Verbose    bool
	ConfigPath string
	SomeString string
)

func main() {
	Execute()
	return
}

var rootCmd = &cobra.Command{
	Use:   "root",
	Short: "the short description shown in the 'help' output.",
	Long: `root description detail
			Long is the long message shown in the 'help <this-command>' output.`,
	Run: func(cmd *cobra.Command, args []string) {
		// Do Stuff Here
		fmt.Printf("root verbose: %v\n", Verbose)
		fmt.Printf("root config: %s\n", ConfigPath)
		fmt.Printf("root string: %s\n", SomeString)
	},
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

var apiCmd = &cobra.Command{
	Use:   "api",
	Short: "api short description",
	Long:  `api long description`,
	Run: func(cmd *cobra.Command, args []string) {
		// Do Stuff Here
		fmt.Printf("api verbose: %v\n", Verbose)
		fmt.Printf("api config: %s\n", ConfigPath)
		fmt.Printf("api string: %s\n", SomeString)
	},
}

var adminCmd = &cobra.Command{
	Use:   "admin",
	Short: "admin short description",
	Long:  `admin long description`,
	Run: func(cmd *cobra.Command, args []string) {
		// Do Stuff Here
		fmt.Printf("admin verbose: %v\n", Verbose)
		fmt.Printf("admin config: %s\n", ConfigPath)
		fmt.Printf("admin string: %s\n", SomeString)
	},
}

var apiChildCmd = &cobra.Command{
	Use:   "apiChild",
	Short: "apiChild short description",
	Long:  `apiChild long description`,
	Run: func(cmd *cobra.Command, args []string) {
		// Do Stuff Here
		fmt.Printf("apiChild verbose: %v\n", Verbose)
		fmt.Printf("apiChild config: %s\n", ConfigPath)
        fmt.Printf("apiChild string: %s\n", SomeString)
	},
}

func init() {
	rootCmd.AddCommand(apiCmd, adminCmd)
	apiCmd.AddCommand(apiChildCmd)
	// persistent是全局选项,对应的方法为PersistentFlags
	rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "全局版本")
	rootCmd.PersistentFlags().StringVarP(&SomeString, "string", "s", "null", "字符串")
	// local为本地选项,对应方法为Flags,只对指定的Command生效
	apiCmd.Flags().StringVarP(&ConfigPath, "config", "c", "", "读取文件路径")
}

// persistent是全局选项,对应的方法为PersistentFlags

rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "全局版本")

rootCmd.PersistentFlags().StringVarP(&SomeString, "string", "s", "null", "字符串")

// local为本地选项,对应方法为Flags,只对指定的Command生效

apiCmd.Flags().StringVarP(&ConfigPath, "config", "c", "", "读取文件路径")

四. 结果

Go 复制代码
go run ./main.go -v -s aaa
root verbose: true
root config: 
root string: aaa
Go 复制代码
 go run ./main.go api -v -s aaa -c config
api verbose: true
api config: config
api string: aaa
Go 复制代码
go run ./main.go api apiChild -v -s aaa          
apiChild verbose: true
apiChild config: 
apiChild string: aaa

只有api可以设置-c参数

五. 添加svc库

svc库将服务分为初始化、启动服务、结束服务三个阶段。

引入svc包

复制代码
go get -u github.com/judwhite/go-svc

与cobra结合,如下为项目启动示例代码

Go 复制代码
func main() {
	Execute()
	return
}

var rootCmd = &cobra.Command{
	Use:   "server",
	Short: "",
	Long:  "",
	Run: func(cmd *cobra.Command, args []string) {

	},
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}


type Application struct {
}

var cfgFile *string

var startCmd = &cobra.Command{
	Use:   "start",
	Short: "start the api server",
	Long: `usage example:
	server(.exe) start -c apollo.json
	start the server`,
	Run: func(cmd *cobra.Command, args []string) {
		app := &Application{}
		if err := svc.Run(app, syscall.SIGINT, syscall.SIGTERM); err != nil {
			fmt.Println(err)
		}
	},
}

func init() {
	rootCmd.AddCommand(startCmd)
	cfgFile = startCmd.Flags().StringP("config", "c", "", "config file (required)")
	startCmd.MarkFlagRequired("config")
}

func (app *Application) Init(env svc.Environment) error {
	// do init

	return nil
}

func (app *Application) Start() error {
	// do start

	return nil
}

func (app *Application) Stop() error {
	// do stop

	return nil
}
相关推荐
Lovely Ruby8 小时前
前端er Go-Frame 的学习笔记:实现 to-do 功能(三),用 docker 封装成镜像,并且同时启动前后端数据库服务
前端·学习·golang
互亿无线明明14 小时前
如何为全球业务构建可扩展的“群发国际短信接口”?
java·c++·python·golang·eclipse·php·erlang
张较瘦_15 小时前
[论文阅读] 软件工程 - 供应链 | 从Log4Shell到Go组件漏洞:一篇文看懂开源依赖安全的核心痛点与解决方案
论文阅读·golang·开源
wadesir15 小时前
Go语言反射之结构体的深比较(详解reflect.DeepEqual在结构体比较中的应用)
开发语言·后端·golang
古城小栈18 小时前
Go 72变之 编成 C语言
c语言·python·golang
卿雪18 小时前
认识Redis:Redis 是什么?好处?业务场景?和MySQL的区别?
服务器·开发语言·数据库·redis·mysql·缓存·golang
foxsen_xia19 小时前
go(基础10)——错误处理
开发语言·后端·golang
雨中散步撒哈拉19 小时前
21、做中学 | 高一上期 |Golang单元测试
golang·单元测试·log4j
熬了夜的程序员19 小时前
【RUSTFS】rustfs的go语言sdk
开发语言·后端·golang
卿雪20 小时前
缓存异常:缓存击穿、缓存穿透、缓存雪崩 及其解决方案
java·数据库·redis·python·mysql·缓存·golang