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 } |