GoFrame 命令管理-命令行對象

2022-03-28 16:12 更新

基本介紹

大部分場景下,我們通過?Command?命令行對象來管理單個或多個命令,并且使用默認的命令行解析規(guī)則(不用顯式使用?Parser?解析器)即可。?Command?對象定義如下:

詳細請參考接口文檔:https://pkg.go.dev/github.com/gogf/gf/v2/os/gcmd@master#Command

// Command holds the info about an argument that can handle custom logic.
type Command struct {
	Name          string        // Command name(case-sensitive).
	Usage         string        // A brief line description about its usage, eg: gf build main.go [OPTION]
	Brief         string        // A brief info that describes what this command will do.
	Description   string        // A detailed description.
	Arguments     []Argument    // Argument array, configuring how this command act.
	Func          Function      // Custom function.
	FuncWithValue FuncWithValue // Custom function with output parameters that can interact with command caller.
	HelpFunc      Function      // Custom help function
	Examples      string        // Usage examples.
	Additional    string        // Additional info about this command, which will be appended to the end of help info.
	Strict        bool          // Strict parsing options, which means it returns error if invalid option given.
	Config        string        // Config node name, which also retrieves the values from config component along with command line.
	parent        *Command      // Parent command for internal usage.
	commands      []*Command    // Sub commands of this command.
}

由于對象均有詳細的注釋,這里不再贅述。

回調方法

?Command?對象支持3個回調方法:

  • ?Func?我們一般需要自定義這個回調方法,用于實現(xiàn)當前命令執(zhí)行的操作。
  • ?FuncWithValue?方法同?Func?,只不過支持返回值,往往用于命令行相互調用的場景,一般項目用不到。
  • ?HelpFunc?自定義幫助信息,一般來說沒有太大必要,因為?Command?對象能夠自動生成幫助信息。

我們主要關注?Func?回調方法即可,其他方法大家感興趣可以自行研究。

Func回調

方法定義:

// Function is a custom command callback function that is bound to a certain argument.
type Function func(ctx context.Context, parser *Parser) (err error)

可以看到,在回調方法內部,我們通過?parser?對象獲取解析參數(shù)和選項,并通過返回?error?來告訴上層調用方法是否執(zhí)行成功。

使用示例:

package main

import (
	"context"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"
	"github.com/gogf/gf/v2/os/gctx"
)

var (
	Main = &gcmd.Command{
		Name:        "main",
		Brief:       "start http server",
		Description: "this is the command entry for starting your http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			s := g.Server()
			s.BindHandler("/", func(r *ghttp.Request) {
				r.Response.Write("Hello world")
			})
			s.SetPort(8199)
			s.Run()
			return
		},
	}
)

func main() {
	Main.Run(gctx.New())
}

這也是大部分項目的啟動命令行對象的樣子,大部分項目只有一個啟動入口,并且只會有一個回調方法實現(xiàn)。

幫助信息生成

?Command?對象雖然可以自定義?HelpFunc?幫助回調方法,但?Command?對象可以自動生成?Help?使用幫助信息,大部分場景下無需自定義。并且?gcmd?組件默認內置了支持了?h/help?選項,因此使用?gcmd?組件的程序可以通過這兩個選項自動生成?Help?幫助信息。

我們來看一個例子,我們先通過?go build main.go?把上面的例子編譯為二進制?main?文件,然后來簡單看一下只有一個命令場景下自動生成的幫助信息:

$ ./main -h 
USAGE
    main [OPTION]

DESCRIPTION
    this is the command entry for starting your http server  

層級命令管理

父命令與子命令

一個?Command?命令可以添加子級命令,當?Command?存在子級命令時,自己便成為了父級命令。子級命令也可以添加自己的子級命令,以此類推,形成層級命令關系。父級命令和子級命令都可以有自己的回調方法,不過大部分場景下,一旦?Command?成為了父級命令,回調方法往往都沒有太大存在的必要。我們通常通過?AddCommand?方法為?Command?添加子級命令:

// AddCommand adds one or more sub-commands to current command.
func (c *Command) AddCommand(commands ...*Command) error

層級命令使用示例

我們來演示一個多命令管理的示例。我們將上面的例子改進一下,增加兩個子級命令。

package main

import (
	"context"
	"fmt"

	"github.com/gogf/gf/v2/os/gcmd"
	"github.com/gogf/gf/v2/os/gctx"
)

var (
	Main = &gcmd.Command{
		Name:        "main",
		Brief:       "start http server",
		Description: "this is the command entry for starting your process",
	}
	Http = &gcmd.Command{
		Name:        "http",
		Brief:       "start http server",
		Description: "this is the command entry for starting your http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			fmt.Println("start http server")
			return
		},
	}
	Grpc = &gcmd.Command{
		Name:        "grpc",
		Brief:       "start grpc server",
		Description: "this is the command entry for starting your grpc server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			fmt.Println("start grpc server")
			return
		},
	}
)

func main() {
	err := Main.AddCommand(Http, Grpc)
	if err != nil {
		panic(err)
	}
	Main.Run(gctx.New())
}

可以看到,我們通過?AddCommand?命令為主命令增加了兩個子級命令?http/grpc?,分別用于開啟?http/grpc?服務。當存在子級命令式,父命令往往便沒有?Func?回調定義的必要了,因此我們這里去掉了?main?命令的?Func?定義。

我們編譯后來執(zhí)行一下看看效果:

$ main     
USAGE
    main COMMAND [OPTION]

COMMAND
    http    start http server
    grpc    start grpc server

DESCRIPTION
    this is the command entry for starting your process

使用?http?命令:

$ main http
start http server

使用?grpc?命令:

$ main grpc
start grpc server


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號