2019-02-02 16:18:25 +08:00
|
|
|
|
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
2019-01-23 13:01:58 +08:00
|
|
|
|
//
|
|
|
|
|
// 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,
|
2019-02-02 16:18:25 +08:00
|
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
2019-01-23 13:01:58 +08:00
|
|
|
|
|
|
|
|
|
package cmdenv
|
|
|
|
|
|
|
|
|
|
import (
|
2019-04-11 09:26:52 +08:00
|
|
|
|
"github.com/gogf/gf/g/container/gvar"
|
|
|
|
|
"os"
|
|
|
|
|
"regexp"
|
|
|
|
|
"strings"
|
2019-01-23 13:01:58 +08:00
|
|
|
|
)
|
|
|
|
|
|
2019-04-11 09:26:52 +08:00
|
|
|
|
var (
|
|
|
|
|
// Console options.
|
|
|
|
|
cmdOptions = make(map[string]string)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
|
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]
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-01-23 13:01:58 +08:00
|
|
|
|
// 获取指定名称的命令行参数,当不存在时获取环境变量参数,皆不存在时,返回给定的默认值。
|
|
|
|
|
// 规则:
|
|
|
|
|
// 1、命令行参数以小写字母格式,使用: gf.包名.变量名 传递;
|
|
|
|
|
// 2、环境变量参数以大写字母格式,使用: GF_包名_变量名 传递;
|
2019-05-10 13:38:06 +08:00
|
|
|
|
func Get(key string, def...interface{}) *gvar.Var {
|
2019-01-23 13:01:58 +08:00
|
|
|
|
value := interface{}(nil)
|
|
|
|
|
if len(def) > 0 {
|
|
|
|
|
value = def[0]
|
|
|
|
|
}
|
2019-04-11 09:26:52 +08:00
|
|
|
|
if v, ok := cmdOptions[key]; ok {
|
2019-01-23 13:01:58 +08:00
|
|
|
|
value = v
|
|
|
|
|
} else {
|
|
|
|
|
key = strings.ToUpper(strings.Replace(key, ".", "_", -1))
|
2019-04-11 09:26:52 +08:00
|
|
|
|
if v := os.Getenv(key); v != "" {
|
2019-01-23 13:01:58 +08:00
|
|
|
|
value = v
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return gvar.New(value, true)
|
|
|
|
|
}
|