-
Notifications
You must be signed in to change notification settings - Fork 0
/
configuration.go
115 lines (97 loc) · 2.03 KB
/
configuration.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
package goutil
import (
"encoding/json"
"os"
"reflect"
"strconv"
)
// Configuration is a function for get info configuration
func Configuration(osFile *os.File, model interface{}) error {
decoder := json.NewDecoder(osFile)
err := decoder.Decode(model)
if err != nil {
return err
}
if err := envConfiguration(model); err != nil {
return err
}
return err
}
func envConfiguration(req interface{}) error {
v := reflect.ValueOf(req)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
return setEnv(v.Type(), v)
}
func setEnv(t reflect.Type, v reflect.Value) error {
if v.Kind() == reflect.Struct {
for i := 0; i < t.NumField(); i++ {
f := v.Field(i)
k := v.Field(i).Kind()
if k == reflect.Struct {
if err := setEnv(f.Type(), f); err != nil {
return err
}
continue
}
val := os.Getenv(t.Field(i).Tag.Get("env"))
if val == "" {
continue
}
switch k {
case reflect.String:
f.SetString(val)
case reflect.Int:
valInt, err := strconv.ParseInt(val, 10, 0)
if err != nil {
return err
}
f.SetInt(valInt)
case reflect.Int8:
valInt, err := strconv.ParseInt(val, 10, 8)
if err != nil {
return err
}
f.SetInt(valInt)
case reflect.Int16:
valInt, err := strconv.ParseInt(val, 10, 16)
if err != nil {
return err
}
f.SetInt(valInt)
case reflect.Int32:
valInt, err := strconv.ParseInt(val, 10, 32)
if err != nil {
return err
}
f.SetInt(valInt)
case reflect.Int64:
valInt, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return err
}
f.SetInt(valInt)
case reflect.Bool:
valBool, err := strconv.ParseBool(val)
if err != nil {
return err
}
f.SetBool(valBool)
case reflect.Float32:
valFloat, err := strconv.ParseFloat(val, 32)
if err != nil {
return err
}
f.SetFloat(valFloat)
case reflect.Float64:
valFloat, err := strconv.ParseFloat(val, 64)
if err != nil {
return err
}
f.SetFloat(valFloat)
}
}
}
return nil
}