Golang Cobra简介安装使用(一)

Cobra提供的功能

  • 简易的子命令行模式,如 app server, app fetch等等
  • 完全兼容posix命令行模式
  • 嵌套子命令subcommand
  • 支持全局,局部,串联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信息
  • 可选的紧密集成的viper apps

安装cobra

1.创建gomod文件

Golang Cobra简介安装使用(一)_第1张图片

 

 

2.设置gomod,通过gomod拉取cobra

GOPROXY=https://goproxy.cn,direct, https://github.com;GO111MODULE=on

Golang Cobra简介安装使用(一)_第2张图片

4. 控制台拉取包

go get -v github.com/spf13/cobra

Golang Cobra简介安装使用(一)_第3张图片

go install github.com/spf13/cobra/cobra

5.创建demo,进入到bin目录下执行cobra init --pkg-name demo

出现如下目录:

Golang Cobra简介安装使用(一)_第4张图片 

6.运行

main.go中的import中demo需要修改为module内容,否则会编译失败 

Golang Cobra简介安装使用(一)_第5张图片 

 执行

go run main.go

可以看到

E:\workspace\cobraDemo>go run main.go
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.

使用cobra

1.添加子命令
使用cobra add test 添加子命令test,在cmd目录下生成test.go

E:\workspace\cobraDemo>cobra add test
test created at E:\workspace\cobraDemo

Golang Cobra简介安装使用(一)_第6张图片

验证

go run main.go test

 打印

E:\workspace\cobraDemo>go run main.go test
test called 

2. root修改应用示例

package cmd

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

	"github.com/spf13/viper"
)

var cfgFile string
//增加name参数
var name string

var rootCmd = &cobra.Command{
	Use:   "demo",
	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.`,
	Run: func(cmd *cobra.Command, args []string) {
		//赋值
		fmt.Println(name)
	},
}

func Execute() {
	cobra.CheckErr(rootCmd.Execute())
}

func init() {
	cobra.OnInitialize(initConfig)
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.demo.yaml)")
	rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
	//参数给变量赋值
	rootCmd.PersistentFlags().StringVar(&name, "name", "", "name demo")
}

func initConfig() {
	if cfgFile != "" {
		viper.SetConfigFile(cfgFile)
	} else {
		home, err := os.UserHomeDir()
		cobra.CheckErr(err)
		viper.AddConfigPath(home)
		viper.SetConfigType("yaml")
		viper.SetConfigName(".demo")
	}

	viper.AutomaticEnv()
	if err := viper.ReadInConfig(); err == nil {
		fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
	}
}
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:
  demo [flags]
  demo [command]

Available Commands:
  completion  generate the autocompletion script for the specified shell
  help        Help about any command
  test        A brief description of your command

Flags:
      --config string   config file (default is $HOME/.demo.yaml)
  -h, --help            help for demo
      --name string     name demo
  -t, --toggle          Help message for toggle

Use "demo [command] --help" for more information about a command.

执行,输出:

E:\workspace\cobraDemo>go run main.go --name zhangsan
zhangsan

你可能感兴趣的:(golang,开发语言,后端)