-
Notifications
You must be signed in to change notification settings - Fork 1
/
env.go
119 lines (100 loc) · 2.47 KB
/
env.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package factorcfg
import (
"os"
"strings"
)
type EnvGetValue func(string) string
func envGetValue(key string) string {
return os.Getenv(key)
}
type Env struct{}
func NewEnv() *Env {
return &Env{}
}
func (e *Env) All() (map[string]interface{}, error) {
env := os.Environ()
m := make(map[string]interface{})
for _, pair := range env {
kv := strings.SplitN(pair, "=", 2)
if kv != nil && len(kv) >= 2 {
m[kv[0]] = kv[1]
}
}
if len(m) > 0 {
return m, nil
}
return nil, nil
}
func (e *Env) Tag() string {
return "env"
}
// func (e *Env) Apply(spec interface{}) error {
// return envApply(envGetValue, spec)
// }
// func envApply(getValue EnvGetValue, spec interface{}) error {
// s := reflect.ValueOf(spec)
// if s.Kind() != reflect.Ptr {
// return errors.New("spec must be a pointer to a struct")
// }
// s = s.Elem()
// if s.Kind() != reflect.Struct {
// return ErrInvalidSpecification
// }
// return envapply(getValue, s)
// }
// func envapply(getValue EnvGetValue, s reflect.Value) error {
// typeOfSpec := s.Type()
// for i := 0; i < s.NumField(); i++ {
// f := s.Field(i)
// t := typeOfSpec.Field(i)
// if f.CanSet() {
// fieldName := typeOfSpec.Field(i).Name
// if f.Kind() == reflect.Struct {
// envapply(getValue, f)
// continue
// }
// key := t.Tag.Get("env")
// value := getValue(key)
// if value == "" {
// continue
// }
// switch f.Kind() {
// case reflect.String:
// f.SetString(value)
// case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
// intValue, err := strconv.ParseInt(value, 0, f.Type().Bits())
// if err != nil {
// return &ParseError{
// FieldName: fieldName,
// TypeName: f.Kind().String(),
// Value: value,
// }
// }
// f.SetInt(intValue)
// case reflect.Bool:
// boolValue, err := strconv.ParseBool(value)
// if err != nil {
// return &ParseError{
// FieldName: fieldName,
// TypeName: f.Kind().String(),
// Value: value,
// }
// }
// f.SetBool(boolValue)
// case reflect.Float32:
// floatValue, err := strconv.ParseFloat(value, f.Type().Bits())
// if err != nil {
// return &ParseError{
// FieldName: fieldName,
// TypeName: f.Kind().String(),
// Value: value,
// }
// }
// f.SetFloat(floatValue)
// case reflect.Slice:
// f.Set(reflect.ValueOf(trimsplit(value, ",")))
// }
// }
// }
// return nil
// }