go插件cobra命令用法

需要引入包 “github.com/spf13/cobra”
包名 command
我最终想实现的效果是 输入命令,其中最后一个是参数

>>command node start 交水费
>>不要企图爱上哥,哥只是个传说: [交水费]
>>command node start 交电费
>>不要企图爱上哥,哥只是个传说: [交电费]

一言不合就上代码

 1. 这是主类,最重要的一句是

mainCmd.AddCommand(node.Cmd())

package main
import (
    "fmt"
    "os"
    "command/node"
    "github.com/spf13/cobra"
)
var versionFlag bool
var mainCmd = &cobra.Command{
    Use: "command",
    PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
        return nil
    },
    Run: func(cmd *cobra.Command, args []string) {
        if versionFlag {
            //        version.Print()
        } else {
            cmd.HelpFunc()(cmd, args)
        }
        fmt.Println(args)
    },
}
func main() {
    mainCmd.AddCommand(node.Cmd())
    if mainCmd.Execute() != nil {
        os.Exit(1)
    }
}
2.  你猜到了,还有node文件夹下的node.go
package import (
    "fmt"
    "github.com/spf13/cobra"
)
const nodeFuncName = "node"
var (
    stopPidFile string
)
// Cmd returns the cobra command for Node
func Cmd() *cobra.Command {
    nodeCmd.AddCommand(startCmd())
    return nodeCmd
}
var nodeCmd = &cobra.Command{
    Use:   nodeFuncName,
    Short: fmt.Sprintf("%s specific commands.", nodeFuncName),
    Long:  fmt.Sprintf("%s specific commands.", nodeFuncName),
}
3.  start.go文件
package node
import (
    "fmt"
    "github.com/spf13/cobra"
)
var chaincodeDevMode bool
func startCmd() *cobra.Command {   
    return nodeStartCmd
}
var nodeStartCmd = &cobra.Command{
    Use:   "start",
    Short: "Starts the node.",
    Long:  `Starts a node that interacts with the network.`,
    RunE: func(cmd *cobra.Command, args []string) error {
        return serve(args)
    },
}
func serve(args []string) error {
    fmt.Println("不要企图爱上哥,哥只是个传说:", args)
    return nil
}
4.  好吧,运行去吧。恭喜你学会了cobra

你可以输入

>>command --help
>>command node 
>>command node --help
>>command start --help

其实所有的显示输出都是可以定制的。具体见"github.com/spf13/cobra"
这个command.go 的Command struct的结构

不要企图爱上哥,哥只是个传说!

你可能感兴趣的:(go插件)