GoFrame 命令管理-Parser解析

2022-03-29 15:31 更新

基本介紹

命名行解析最主要的是針對于選項的解析,?gcmd?組件提供了?Parse?方法,用于自定義解析選項,包括有哪些選項名稱,每個選項是否帶有數(shù)值。根據(jù)這一配置便可將所有的參數(shù)和選項進行解析歸類。

大部分場景下,我們并不需要顯式創(chuàng)建?Parser?對象,因為我們有層級管理以及對象管理方式來管理多命令。但底層仍然是采用?Parser?方式實現(xiàn),因此本章節(jié)大家了解原理即可。

相關(guān)方法:

更多?Parser?方法請參考接口文檔:https://pkg.go.dev/github.com/gogf/gf/v2/os/gcmd#Parser

func Parse(supportedOptions map[string]bool, strict ...bool) (*Parser, error)
func ParseWithArgs(args []string, supportedOptions map[string]bool, strict ...bool) (*Parser, error)
func ParserFromCtx(ctx context.Context) *Parser
func (p *Parser) GetArg(index int, def ...string) *gvar.Var
func (p *Parser) GetArgAll() []string
func (p *Parser) GetOpt(name string, def ...interface{}) *gvar.Var
func (p *Parser) GetOptAll() map[string]string

解析示例:

parser, err := gcmd.Parse(g.MapStrBool{
	"n,name":    true,
	"v,version": true,
	"a,arch":    true,
	"o,os":      true,
	"p,path":    true,
})

可以看到,選項輸入?yún)?shù)其實是一個?map?類型。其中鍵值為選項名稱,同一個選項的不同名稱可以通過,符號進行分隔。比如,該示例中?n?和?name?選項是同一個選項,當用戶輸入?-n john?的時候,?n?和?name?選項都會獲得到數(shù)據(jù)?john?。

而鍵值是一個布爾類型,標識該選項是否需要解析參數(shù)。這一選項配置是非常重要的,因為有的選項是不需要獲得數(shù)據(jù)的,僅僅作為一個標識。例如,?-f force?這個輸入,在需要解析數(shù)據(jù)的情況下,選項?f?的值為?force?;而在不需要解析選項數(shù)據(jù)的情況下,其中的?force?便是命令行的一個參數(shù),而不是選項。

使用示例

func ExampleParse() {
	os.Args = []string{"gf", "build", "main.go", "-o=gf.exe", "-y"}
	p, err := gcmd.Parse(g.MapStrBool{
		"o,output": true,
		"y,yes":    false,
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(p.GetOpt("o"))
	fmt.Println(p.GetOpt("output"))
	fmt.Println(p.GetOpt("y") != nil)
	fmt.Println(p.GetOpt("yes") != nil)
	fmt.Println(p.GetOpt("none") != nil)

	// Output:
	// gf.exe
	// gf.exe
	// true
	// true
	// false
}


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號