代碼
//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, "打印系統(tǒng)版本")
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 打印系統(tǒng)版本
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