This commit is contained in:
timest 2018-07-10 22:27:19 +08:00
parent 4ed55b5d62
commit 3d591d9186

19
env.go
View File

@ -10,7 +10,7 @@ import (
) )
var ( var (
DEFAULT_SEPARATOR = "_" defaultSep = "_"
) )
func upper(v string) string { func upper(v string) string {
@ -19,7 +19,7 @@ func upper(v string) string {
func Fill(v interface{}) error { func Fill(v interface{}) error {
if reflect.ValueOf(v).Kind() != reflect.Ptr { if reflect.ValueOf(v).Kind() != reflect.Ptr {
return fmt.Errorf("env.Fill 只接受指针类型的值") return fmt.Errorf("only the pointer to a struct is supported")
} }
ind := reflect.Indirect(reflect.ValueOf(v)) ind := reflect.Indirect(reflect.ValueOf(v))
prefix := upper(ind.Type().Name()) prefix := upper(ind.Type().Name())
@ -30,9 +30,9 @@ func Fill(v interface{}) error {
return nil return nil
} }
func combine(p, n string, v string, ok bool) string{ func combine(p, n string, v string, ok bool) string {
if !ok { if !ok {
return p + DEFAULT_SEPARATOR + n return p + defaultSep + n
} }
return p + v + n return p + v + n
} }
@ -44,7 +44,7 @@ func parseBool(v string) (bool, error) {
return strconv.ParseBool(v) return strconv.ParseBool(v)
} }
func fill(pf string, ind reflect.Value) error{ func fill(pf string, ind reflect.Value) error {
for i := 0; i < ind.NumField(); i++ { for i := 0; i < ind.NumField(); i++ {
f := ind.Type().Field(i) f := ind.Type().Field(i)
name := f.Name name := f.Name
@ -75,12 +75,13 @@ func parse(prefix string, f reflect.Value, sf reflect.StructField) error {
df := sf.Tag.Get("default") df := sf.Tag.Get("default")
isRequire, err := parseBool(sf.Tag.Get("require")) isRequire, err := parseBool(sf.Tag.Get("require"))
if err != nil { if err != nil {
return fmt.Errorf("字段:%s require不是合法的布尔值支持: 1 t T true TRUE True.", prefix) return fmt.Errorf("the value of %s is not a valid `member` of bool only "+
"[1 0 t f T F true false TRUE FALSE True False] are supported", prefix)
} }
ev, exist := os.LookupEnv(prefix) ev, exist := os.LookupEnv(prefix)
if !exist && isRequire { if !exist && isRequire {
return fmt.Errorf("%s 是必须的变量,但没有被设置", prefix) return fmt.Errorf("%s is required, but has not been set", prefix)
} }
if !exist && df != "" { if !exist && df != "" {
ev = df ev = df
@ -122,13 +123,13 @@ func parse(prefix string, f reflect.Value, sf reflect.StructField) error {
} }
f.SetUint(uiv) f.SetUint(uiv)
case reflect.Float32: case reflect.Float32:
f32, err := strconv.ParseFloat(ev, 32) f32, err := strconv.ParseFloat(ev, 32)
if err != nil { if err != nil {
return err return err
} }
f.SetFloat(f32) f.SetFloat(f32)
case reflect.Float64: case reflect.Float64:
f64, err := strconv.ParseFloat(ev, 64) f64, err := strconv.ParseFloat(ev, 64)
if err != nil { if err != nil {
return err return err
} }