-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
fill_environments.go
97 lines (78 loc) · 1.96 KB
/
fill_environments.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
package goconfig
import (
"encoding/json"
"errors"
"fmt"
"os"
"reflect"
"strconv"
"strings"
"time"
)
func FillEnvironments(c interface{}) (err error) {
traverse(c, func(i item) {
env := strings.ToUpper(strings.Join(i.Path, "_"))
value := os.Getenv(env)
if "" == value {
return
}
if reflect.TypeOf(time.Duration(0)) == i.Value.Type() {
if d, err := unmarshalDurationString(value); err == nil {
v := int64(d)
set(i.Ptr, &v)
}
} else if reflect.Bool == i.Kind {
if v, err := strconv.ParseBool(value); nil == err {
set(i.Ptr, &v)
}
} else if reflect.Float64 == i.Kind {
if v, err := strconv.ParseFloat(value, 64); nil == err {
set(i.Ptr, &v)
}
} else if reflect.Float32 == i.Kind {
if v, err := strconv.ParseFloat(value, 32); nil == err {
w := float32(v)
set(i.Ptr, &w)
}
} else if reflect.Int64 == i.Kind {
if v, err := strconv.ParseInt(value, 10, 64); nil == err {
set(i.Ptr, &v)
}
} else if reflect.Int32 == i.Kind {
if v, err := strconv.ParseInt(value, 10, 64); nil == err {
w := int32(v)
set(i.Ptr, &w)
}
} else if reflect.Int == i.Kind {
if v, err := strconv.ParseInt(value, 10, strconv.IntSize); nil == err {
w := int(v)
set(i.Ptr, &w)
}
} else if reflect.String == i.Kind {
set(i.Ptr, &value)
} else if reflect.Uint64 == i.Kind {
if v, err := strconv.ParseUint(value, 10, 64); nil == err {
set(i.Ptr, &v)
}
} else if reflect.Uint32 == i.Kind {
if v, err := strconv.ParseUint(value, 10, 32); nil == err {
w := uint32(v)
set(i.Ptr, &w)
}
} else if reflect.Uint == i.Kind {
if v, err := strconv.ParseUint(value, 10, strconv.IntSize); nil == err {
w := uint(v)
set(i.Ptr, &w)
}
} else if reflect.Slice == i.Kind {
jsonErr := json.Unmarshal([]byte(value), i.Ptr)
if jsonErr != nil {
err = errors.New(fmt.Sprintf(
"'%s' should be a JSON array: %s",
env, jsonErr.Error(),
))
}
}
})
return
}