美文网首页
spf13 cobra代码示例

spf13 cobra代码示例

作者: 莫名FCJ | 来源:发表于2017-11-02 12:36 被阅读119次

代码

https://github.com/fengchunjian/goexamples/cobra

//main.go
package main

import (
    "fmt"
    "github.com/fengchunjian/goexamples/cobra/node"
    "github.com/spf13/cobra"
    "os"
)

var versionFlag bool

var mainCmd = &cobra.Command{
    Use: "command",
    Run: func(cmd *cobra.Command, args []string) {
        if versionFlag {
            fmt.Println("目前版本为1.0.0")
        } else {
            cmd.HelpFunc()(cmd, args)
        }
    },
}

func main() {
    mainFlags := mainCmd.PersistentFlags()
    mainFlags.BoolVarP(&versionFlag, "version", "v", false, "打印系统版本")

    mainCmd.AddCommand(node.Cmd())
    if mainCmd.Execute() != nil {
        os.Exit(1)
    }
}
//node/node.go 
package node

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

var nodeCmd = &cobra.Command{
    Use:   "node",
    Short: fmt.Sprint("这是node命令很短的介绍"),
    Long:  fmt.Sprint("这是node命令很长很长很长的介绍"),
}

func Cmd() *cobra.Command {
    nodeCmd.AddCommand(startCmd())
    return nodeCmd
}

//node/start.go 
package node

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

var nodeStartCmd = &cobra.Command{
    Use:   "start",
    Short: "这是node start命令很短的介绍",
    Long:  "这是node start命令很长很长很长的介绍",
    RunE: func(cmd *cobra.Command, args []string) error {
        return serve(args)
    },
}

func startCmd() *cobra.Command {
    return nodeStartCmd
}

func serve(args []string) error {
    fmt.Println("测试使用node start命令", args)
    return nil
}

编译

go build -o command

运行

./command
./command -h
./command --help
./command 
Usage:
  command [flags]
  command [command]

Available Commands:
  help        Help about any command
  node        这是node命令很短的介绍

Flags:
  -h, --help      help for command
  -v, --version   打印系统版本

Use "command [command] --help" for more information about a command.
./command -v
目前版本为1.0.0
./command node
./command node -h
./command node --help
这是node命令很长很长很长的介绍

Usage:
  command node [command]

Available Commands:
  start       这是node start命令很短的介绍

Flags:
  -h, --help   help for node

Use "command node [command] --help" for more information about a command.
./command node start -h
./command node start --help
这是node start命令很长很长很长的介绍

Usage:
  command node start [flags]

Flags:
  -h, --help   help for start
./command node start 测试

测试使用node start命令 [测试]

参考文档

go插件cobra命令用法
http://blog.csdn.net/qq_27809391/article/details/54089774

相关文章

网友评论

      本文标题:spf13 cobra代码示例

      本文链接:https://www.haomeiwen.com/subject/lbuopxtx.html