golang使用cobra - Go语言中文社区

golang使用cobra


cobra是golang里面一个cli库,地址 https://github.com/spf13/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信息

    一个简单的练习
    首先安装cobra go get -v github.com/spf13/cobra/cobra
    使用cobra在src目录生成一个简单的工程 cobra init demo
    生成的工程结构如图
    这里写图片描述
    cmd/root.go

package cmd

import (
    "demo/imp"
    "fmt"
    "os"

    "github.com/spf13/cobra"
)

var name string

var age int

var rootCmd = &cobra.Command{
    Use:   "demo",
    Short: "this is a test",
    Long:  `this is a test long `,
    Run: func(cmd *cobra.Command, args []string) {
        if len(name) == 0 {
            cmd.Help()
            return
        }
        imp.Show(name, age)
    },
}

// 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() {
    if err := rootCmd.Execute(); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

func init() {
    rootCmd.Flags().StringVarP(&name, "name", "n", "", "person's name")
    rootCmd.Flags().IntVarP(&age, "age", "a", 0, "Person's age")

}

cmd/imp/imp.go

package imp
import (
    "fmt"
)

func Show(name string, age int) {
    fmt.Printf("My Name is %s,My age is %dn", name, age)
}

使用go build . 编译后运行如下

Administrator@P-V-12 MINGW64 /e/goproject/src/demo
$ ./demo.exe --name tom --age 25
My Name is tom,My age is 25

Administrator@P-V-12 MINGW64 /e/goproject/src/demo
$ ./demo.exe -n tom -a 25
My Name is tom,My age is 25

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

package cmd

import (
    "fmt"

    "github.com/spf13/cobra"
)

// testCmd represents the test command
var testCmd = &cobra.Command{
    Use:   "test",
    Short: "id test",
    Long: `this is a id test`,
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("test called")
    },
}

func init() {
    rootCmd.AddCommand(testCmd)
}

运行效果如下

Administrator@P-V-12 MINGW64 /e/goproject/src/demo
$ ./demo.exe  test
test called
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/chuan_yu_chuan/article/details/79307589
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-08-28 20:03:57
  • 阅读 ( 2750 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢