13518219792

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

创新互联GoFrame教程:GoFrame命令管理-基础方法

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

创新互联建站专注于中大型企业的网站制作、成都网站建设和网站改版、网站营销服务,追求商业策划与数据分析、创意艺术与技术开发的融合,累计客户1000+,服务满意度达97%。帮助广大客户顺利对接上互联网浪潮,准确优选出符合自己需要的互联网运用,我们将一直专注品牌网站设计和互联网程序开发,在前进的路上,与客户一起成长!

常用方法

更多组件方法请参考接口文档: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*参数获取

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

使用示例:

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*选项获取

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

使用示例:

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
}

网站标题:创新互联GoFrame教程:GoFrame命令管理-基础方法
标题链接:http://cdbrznjsb.com/article/copschh.html

其他资讯

让你的专属顾问为你服务