/
model_mapper.go
234 lines (212 loc) · 5.63 KB
/
model_mapper.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/**
env_parser performs parsing of the environment variable
and sets the passed struct with value read from the
environment.
Value for each of the struct variable is set by searching
the corresponding name tag in the environment.
Author : shalin LK <shalinkktl@gmail.com>
*/
package env_parser
import (
"errors"
"os"
"reflect"
"strconv"
"strings"
"github.com/HiFX/env_parser/models"
)
const (
APP_TAG = "env"
OPTIONAL = "optional"
MANDATORY = "mandatory"
)
//EnvToStruct is the core object of the environment
//parser on which mapping function is defined.
type EnvToStruct struct {
appName string
separator string
}
//NewEnvParser returns an object of EnvToStruct
func NewEnvParser() EnvToStruct {
e := EnvToStruct{}
return e
}
//Name allows to set name of the application.
//If name is set, parser will append the name of
//the application as prefix with each name tag of
//the variable in the struct.
func (e *EnvToStruct) Name(name string) {
e.appName = name
}
//Separator appends the supplied prefix to be used
//as a separator for the app name and the tag name of
//the variable.
//Eg app name being 'demo' and separator being '_'
//then the phrase 'demo_' will be prefixed with
//each name tag of the variable in the struct.
func (e *EnvToStruct) Separator(sep string) {
e.separator = sep
}
//Map performs the mapping of the environment value
//to the struct.
//source is the structure to which environment values
//are to be mapped.
func (e EnvToStruct) Map(source interface{}) error {
if source == nil {
return errors.New("ivalid source;")
}
rType := reflect.TypeOf(source)
if rType.Kind() != reflect.Ptr {
return errors.New("Expects pointer to target object")
}
rType = rType.Elem()
if rType.Kind() != reflect.Struct {
return errors.New("Expects pointer to struct")
}
rFieldNum := rType.NumField()
metaHolder := make(map[int]fieldMeta, rFieldNum)
for i := 0; i < rFieldNum; i++ {
rTFi := rType.Field(i)
thisMeta := fieldMeta{}
thisMeta.position = i
rFTag := rTFi.Tag.Get(APP_TAG)
tagInfo, tagEr := tagParser(rFTag)
if tagEr != nil {
return *tagEr
}
thisMeta.envName = tagInfo.name
thisMeta.mandatory = tagInfo.mandatory
thisMeta.defVal = tagInfo.deftVal
metaHolder[i] = thisMeta
}
metaHolder = e.envToHolder(e.appName+e.separator, metaHolder)
rValue := reflect.ValueOf(source)
if rValue.IsNil() {
return errors.New("pointer to nil obtained.")
}
if rValue.Kind() == reflect.Ptr {
rValue = rValue.Elem()
}
for i := 0; i < rFieldNum; i++ {
rVFi := rValue.Field(i)
rTFi := rType.Field(i)
if rVFi.Kind() == reflect.Ptr {
rVFi = rVFi.Elem()
}
if rVFi.CanSet() {
thisMeta := metaHolder[i]
electedVal, electionError := thisMeta.electValue()
if electionError != nil {
if *electionError == *models.OptionalValueMissing() {
continue
}
return *electionError.Field(rTFi.Name)
}
switch rTFi.Type.Kind() {
case reflect.Int:
intVal, convErr := strconv.Atoi(electedVal)
if convErr != nil {
return *models.InvalidValue().Field(rTFi.Name)
}
rVFi.Set(reflect.ValueOf(intVal))
case reflect.String:
rVFi.Set(reflect.ValueOf(electedVal))
}
}
}
return nil
}
type fieldMeta struct {
position int
envName string
mandatory bool
defVal string
valueHolder string
}
//electValue chooses the best value for the variable in hand.
//The preferences goes as
// 1. The value read from the environment
// 2. The default value
// 3. Corresponding zero value if 1 & 2 fails and the variable
// is set as optional
//Returns error if the value is missing(both in environment
//and as default) and the variable is set to mandatory.
func (f *fieldMeta) electValue() (string, *models.EnvError) {
if f.valueHolder != "" {
return f.valueHolder, nil
} else if f.defVal != "" {
return f.defVal, nil
} else if f.mandatory {
return "", models.MandatoryValueMissing()
}
return "", models.OptionalValueMissing()
}
type tagInfo struct {
name string
mandatory bool
deftVal string
}
//tag parser performs the parsing of the tag.
//Tag assumes the syntax :
// `env:"<env_name>;<mandatory/optional>;<default_value>'
// 1. use ';' to separate the elements of the tag;
// 2. use adjacent ';' to represent missing elements
func tagParser(tag string) (tagInfo, *models.EnvError) {
result := tagInfo{}
if len(tag) == 0 {
return result, nil
}
exploded := strings.Split(tag, ";")
explodedLength := len(exploded)
if explodedLength < 1 {
return result, models.InvalidTag()
}
//1. name
result.name = strings.TrimSpace(exploded[0])
if result.name == "" {
return result, models.InvalidTag()
}
if explodedLength < 2 {
result.mandatory = false
return result, nil
}
//2. optional / mandatory
if exploded[1] == OPTIONAL {
result.mandatory = false
} else if exploded[1] == MANDATORY {
result.mandatory = true
} else {
return result, models.InvalidTag()
}
if explodedLength < 3 {
return result, nil
}
//3. default value
result.deftVal = exploded[2]
return result, nil
}
func (e EnvToStruct) envToHolder(prefix string, appEnvs map[int]fieldMeta) map[int]fieldMeta {
envVars := os.Environ()
//lookUp table construction
lookUpTable := make(map[string]string)
for _, envVal := range envVars {
exploded := strings.Split(envVal, "=")
lookUpTable[exploded[0]] = exploded[1]
}
//cross check with app env
for i, fMeta := range appEnvs {
envVal, found := lookUpTable[prefix+fMeta.envName]
if found {
envVal = envVal
i = i
metaH := fieldMeta{}
metaH.envName = fMeta.envName
metaH.defVal = fMeta.defVal
metaH.valueHolder = envVal
metaH.mandatory = fMeta.mandatory
metaH.position = fMeta.position
appEnvs[i] = metaH
}
}
return appEnvs
}