// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved. // // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, // You can obtain one at https://github.com/gogf/gf. // Package cmdenv provides access to certain variable for both command options and environment. package cmdenv import ( "os" "regexp" "strings" "github.com/gogf/gf/container/gvar" ) var ( // Console options. cmdOptions = make(map[string]string) ) func init() { doInit() } // doInit does the initialization for this package. func doInit() { reg := regexp.MustCompile(`\-\-{0,1}(.+?)=(.+)`) for i := 0; i < len(os.Args); i++ { result := reg.FindStringSubmatch(os.Args[i]) if len(result) > 1 { cmdOptions[result[1]] = result[2] } } } // Get returns the command line argument of the specified . // If the argument does not exist, then it returns the environment variable with specified . // It returns the default value if none of them exists. // // Fetching Rules: // 1. Command line arguments are in lowercase format, eg: gf..; // 2. Environment arguments are in uppercase format, eg: GF__; func Get(key string, def ...interface{}) *gvar.Var { value := interface{}(nil) if len(def) > 0 { value = def[0] } cmdKey := strings.ToLower(strings.Replace(key, "_", ".", -1)) if v, ok := cmdOptions[cmdKey]; ok { value = v } else { envKey := strings.ToUpper(strings.Replace(key, ".", "_", -1)) if v := os.Getenv(envKey); v != "" { value = v } } return gvar.New(value) }