cobra的使用

一、安装cobra

go get -g github.com/spf13/cobra/cobra

这里会报错,如下:

package golang.org/x/sys/unix: unrecognized import path "golang.org/x/sys/unix" (https fetch: Get https://golang.org/x/sys/unix?go-get=1: dial tcp 108.177.120.94:443: i/o timeout)

解决方法:
使用github中的包代替

go get github.com/golang/sys

然后再把它拷到golang.org包下,编译cobra

go build github.com/spf13/cobra/cobra

二、初始化一个项目

cobra init gitee.com/study/testGoPackage/spf13/cobra/demo

生成的目录结构如下:
cobra的使用_第1张图片
切到demo目录下

1.编译并运行

 [[spf:demo shanpengfei$]]  go build -o d main.go 
 [[spf:demo shanpengfei$]]  ./d
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.

2.添加子命令

 [[spf:demo shanpengfei$]]  cobra add te
te created at /Users/shanpengfei/work/goland/src/gitee.com/study/testGoPackage/spf13/cobra/demo/cmd/te.go
 [[spf:demo shanpengfei$]]  go build -o d main.go 
 [[spf:demo shanpengfei$]]  ./d 
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 [command]

Available Commands:
  help        Help about any command
  te          A brief description of your command

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

Use "demo [command] --help" for more information about a command.
 [[spf:demo shanpengfei$]]  ./d te
te called

3.添加参数

代码如下:

import (
	"fmt"
	"github.com/spf13/cobra"
	"os"
)
var (
	name string
)
var cmd  = &cobra.Command{
	Use: "demoSelf",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println(name)
	},
}

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

func init()  {
	cmd.Flags().StringVarP(&name, "name", "n", "spf", "输入名字")
}

执行命令如下:

spf:demoSelf shanpengfei$ go build -o d main.go 
spf:demoSelf shanpengfei$ ./d
spf
spf:demoSelf shanpengfei$ ./d -n a
a
spf:demoSelf shanpengfei$ ./d -h
Usage:
  demoSelf [flags]
  demoSelf [command]

Available Commands:
  bb          
  help        Help about any command

Flags:
  -h, --help          help for demoSelf
  -n, --name string   输入名字 (default "spf")

Use "demoSelf [command] --help" for more information about a command.
spf:demoSelf shanpengfei$ ./d --name b
b

你可能感兴趣的:(golang,cobra)