GoFrame 命令管理-基础方法

2022-03-29 15:31 更新

gcmd​组件提供了常用的基础包方法,可以按照默认的解析规则,直接获取命令行参数及选项。

常用方法

更多组件方法请参考接口文档:https://pkg.go.dev/github.com/gogf/gf/v2/os/gcmd

func Init(args ...string)

func GetArg(index int, def ...string) *gvar.Var
func GetArgAll() []string

func GetOpt(name string, def ...string) *gvar.Var
func GetOptAll() map[string]string

Init自定义命令行

默认情况下,​gcmd​组件会自动从​os.Args​解析获取参数及数据。我们可以通过​Init​方法自定义命令行数据。使用示例:

func ExampleInit() {
	gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
	fmt.Printf(`%#v`, gcmd.GetArgAll())

	// Output:
	// []string{"gf", "build", "main.go"}
}

GetArg*参数获取

参数获取可以通过以下两个方法:

  • GetArg​方法用以获取默认解析的命令行参数,参数通过输入索引位置获取,索引位置从​0​开始,但往往我们需要获取的参数是从​1​开始,因为索引​0​的参数是程序名称。
  • GetArgAll​方法用于获取所有的命令行参数。

使用示例:

func ExampleGetArg() {
	gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
	fmt.Printf(
		`Arg[0]: "%v", Arg[1]: "%v", Arg[2]: "%v", Arg[3]: "%v"`,
		gcmd.GetArg(0), gcmd.GetArg(1), gcmd.GetArg(2), gcmd.GetArg(3),
	)

	// Output:
	// Arg[0]: "gf", Arg[1]: "build", Arg[2]: "main.go", Arg[3]: ""
}

func ExampleGetArgAll() {
	gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
	fmt.Printf(`%#v`, gcmd.GetArgAll())

	// Output:
	// []string{"gf", "build", "main.go"}
}

GetOpt*选项获取

选项获取可以通过以下两个方法:

  • GetOpt​方法用以获取默认解析的命令行选项,选项通过名称获取,并且选项的输入没有顺序性,可以输入到任意的命令行位置。当给定名称的选项数据不存在时,返回​nil​。注意判断不带数据的选项是否存在时,可以通过​GetOpt(name) != nil​方式。
  • GetOptAll​方法用于获取所有的选项。

使用示例:

func ExampleGetOpt() {
	gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
	fmt.Printf(
		`Opt["o"]: "%v", Opt["y"]: "%v", Opt["d"]: "%v"`,
		gcmd.GetOpt("o"), gcmd.GetOpt("y"), gcmd.GetOpt("d", "default value"),
	)

	// Output:
	// Opt["o"]: "gf.exe", Opt["y"]: "", Opt["d"]: "default value"
}

func ExampleGetOptAll() {
	gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
	fmt.Printf(`%#v`, gcmd.GetOptAll())

	// May Output:
	// map[string]string{"o":"gf.exe", "y":""}
}

GetOptWithEnv特性

func GetOptWithEnv(key string, def ...interface{}) *gvar.Var

该方法用于获取命令行中指定的选项数值,如果该选项不存在时,则从环境变量中读取。但是两者的名称规则会不一样。例如:​gcmd.GetOptWithEnv("gf.debug")​将会优先去读取命令行中的​gf.debug​选项,当不存在时,则会去读取​GF_DEBUG​环境变量。

需要注意的是参数命名转换规则:

  • 环境变量会将名称转换为大写,名称中的​.​字符转换为​_​字符。
  • 命令行中会将名称转换为小写,名称中的​_​字符转换为​.​字符。

使用示例:

func ExampleGetOptWithEnv() {
	fmt.Printf("Opt[gf.test]:%s\n", gcmd.GetOptWithEnv("gf.test"))
	_ = genv.Set("GF_TEST", "YES")
	fmt.Printf("Opt[gf.test]:%s\n", gcmd.GetOptWithEnv("gf.test"))

	// Output:
	// Opt[gf.test]:
	// Opt[gf.test]:YES
}


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号