/
conf.go
442 lines (340 loc) · 9.97 KB
/
conf.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package configparser
import (
"reflect"
"errors"
"strconv"
"fmt"
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"flag"
"time"
)
var (
ErrorNotStruct = errors.New("excepted a pointer of struct")
)
func LoadConfFromJson(_struct interface{}, conf map[string]interface{}) {
handleError(getDefaultMap(_struct))
handleError(addMap(_struct, conf))
}
func AutoLoadConfig(moduleName string, _struct interface{}) {
dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
err := loadConfPath(_struct, dir + "/conf/" + moduleName + ".conf")
if err == nil {
return
}
err = loadConfPath(_struct, dir + "/conf/" + moduleName + ".json")
if err == nil {
return
}
err = loadConfPath(_struct, dir + "/" + moduleName + ".conf")
if err == nil {
return
}
err = loadConfPath(_struct, dir + "/" + moduleName + ".json")
if err == nil {
return
}
err = loadConfPath(_struct, dir + "/conf.json")
if err == nil {
return
}
LoadConfDefault(_struct)
}
func LoadConfDefault(_struct interface{}) {
handleError(getDefaultMap(_struct))
}
func LoadConfPath(_struct interface{}, confpath string) {
handleError(loadConfPath(_struct, confpath))
}
func LoadConfFromFlag(_struct interface{}) {
handleError(getDefaultMap(_struct))
handleError(addFlagMap(_struct))
}
func ToJson(_struct interface{}) (map[string]interface{}, error) {
var (
v reflect.Value
t reflect.Type
)
result := make(map[string]interface{})
if reflect.TypeOf(_struct).Kind() == reflect.Ptr {
v = reflect.ValueOf(_struct).Elem()
t = reflect.TypeOf(_struct).Elem()
} else {
v = reflect.ValueOf(_struct)
t = reflect.TypeOf(_struct)
}
if t.Kind() != reflect.Struct {
panic(errors.New("excepted a pointer of struct or a struct"))
}
for i := 0; i < v.NumField(); i++ {
//fieldName := strings.ToLower(t.Field(i).Name)
fieldName := t.Field(i).Name
result[fieldName] = v.Field(i).Interface()
}
val, _ := json.MarshalIndent(result, "", "\t")
fmt.Printf("%v\n", (string)(val))
return result, nil
}
func handleError(err error) {
if err != nil {
fmt.Println("Error When Load Config\n" + err.Error())
os.Exit(-2)
}
}
func loadConfPath(_struct interface{}, confpath string) error {
fmt.Println("Trying load configure from " + confpath)
b, err := ioutil.ReadFile(confpath)
if err != nil {
fmt.Println("load failed :" + err.Error())
return err
}
v := make(map[string]interface{})
err = json.Unmarshal(b, &v)
if err != nil {
fmt.Println("load failed :" + err.Error())
return err
}
if err := getDefaultMap(_struct); err != nil {
fmt.Println("load failed :" + err.Error())
return err
}
if err := addMap(_struct, v); err != nil {
fmt.Println("load failed :" + err.Error())
return err
}
return nil
}
func checkTypeAndPanic(_struct interface{}) (reflect.Value, reflect.Type) {
if reflect.TypeOf(_struct).Kind() != reflect.Ptr {
panic(ErrorNotStruct)
}
v := reflect.ValueOf(_struct).Elem()
t := reflect.TypeOf(_struct).Elem()
if t.Kind() != reflect.Struct {
panic(ErrorNotStruct)
}
return v, t
}
type sliceValue struct {
typ reflect.Type
Vals reflect.Value
setted bool
field string
}
func (s *sliceValue) String() string {
return fmt.Sprintf("%v", s.Vals)
}
func (sl *sliceValue) Set(s string) error {
sl.setted = true
var tmpv interface{}
if s == "" {
tmpv = []interface{}{}
} else {
err := json.Unmarshal(([]byte)(s), &tmpv)
if err != nil {
return fmt.Errorf("In field %s, unmarshal slice error : %s", sl.field, err.Error())
}
}
vm := reflect.ValueOf(tmpv)
tshould := sl.typ
le := vm.Len()
tmpTransed := reflect.MakeSlice(reflect.SliceOf(tshould), le, le)
for i := 0; i < le; i++ {
if reflect.TypeOf(vm.Index(i).Interface()).ConvertibleTo(tshould) {
tmpTransed.Index(i).Set( reflect.ValueOf(vm.Index(i).Interface()).Convert(tshould) )
} else {
return fmt.Errorf("In field %s, have a Un Convertible value, at postion %d", sl.field, i)
}
}
sl.Vals = tmpTransed
return nil
}
func addFlagMap(_struct interface{}) error {
if flag.Parsed() {
return errors.New("error when add flag arguments: parsed flags cann't parse twice")
}
v, t := checkTypeAndPanic(_struct)
slicePostion := []int{}
sliceValues := []*sliceValue{}
for i := 0; i < v.NumField(); i++ {
fieldName := t.Field(i).Name
if !v.Field(i).CanSet() {
continue;
}
pointer := v.Field(i).Addr().Interface()
usage := t.Field(i).Tag.Get("usage")
switch t.Field(i).Type.Kind() {
case reflect.String:
flag.StringVar(pointer.(*string), fieldName, v.Field(i).String(), usage)
case reflect.Bool:
flag.BoolVar(pointer.(*bool), fieldName, v.Field(i).Bool(), usage)
case reflect.Int:
flag.IntVar(pointer.(*int), fieldName, (int)(v.Field(i).Int()), usage)
case reflect.Int64:
if t.Field(i).Type == reflect.TypeOf(time.Second) {
flag.DurationVar(pointer.(*time.Duration), fieldName,
time.Duration(v.Field(i).Int()), usage)
} else {
flag.Int64Var(pointer.(*int64), fieldName, v.Field(i).Int(), usage)
}
case reflect.Float64:
flag.Float64Var(pointer.(*float64), fieldName, v.Field(i).Float(), usage)
case reflect.Slice:
slicePostion = append(slicePostion, i)
sliceValues = append(sliceValues, &sliceValue{
typ: t.Field(i).Type.Elem(),
field: fieldName,
})
flag.Var(sliceValues[len(sliceValues)-1], fieldName, usage)
default:
panic(fmt.Errorf("In field %s, unsupported type", fieldName))
}
}
flag.Parse()
flag.Usage()
for i, pos := range slicePostion {
if sliceValues[i].Vals.Kind() == reflect.Invalid {
v.Field(pos).Set(reflect.MakeSlice(reflect.SliceOf(sliceValues[i].typ),
0, 0))
} else {
v.Field(pos).Set(sliceValues[i].Vals)
}
}
return nil
}
func getDefaultMap(_struct interface{}) error {
v, t := checkTypeAndPanic(_struct)
for i := 0; i < v.NumField(); i++ {
fieldName := t.Field(i).Name
if !v.Field(i).CanSet() {
continue
}
switch raw := t.Field(i).Tag.Get("default"); t.Field(i).Type.Kind() {
case reflect.String:
v.Field(i).SetString(raw)
case reflect.Bool:
if raw == "true" || raw == "TRUE" || raw == "True" || raw == "T" || raw == "t" || raw == "1" {
v.Field(i).SetBool(true)
} else if raw == "" || raw == "false" || raw == "FALSE" || raw == "False" || raw == "F" || raw == "f" || raw == "0" {
v.Field(i).SetBool(false)
} else {
return fmt.Errorf("In field %s, default string can't parse to bool", fieldName)
}
case reflect.Int64, reflect.Int:
if t.Field(i).Type == reflect.TypeOf(time.Duration(0)) {
//if is time duration, progress by time.Duration
dur, err := time.ParseDuration(raw)
if err != nil {
return fmt.Errorf("In field %s, default string can't parse to time.Duration", fieldName)
}
v.Field(i).SetInt((int64)(dur))
} else {
if raw == "" {
v.Field(i).SetInt(0)
continue
}
tmpv, e := strconv.ParseInt(raw, 10, 64)
if e != nil {
return fmt.Errorf("In field %s, default string can't be parse to int", fieldName)
}
v.Field(i).SetInt(tmpv)
}
case reflect.Float64:
if raw == "" {
v.Field(i).SetFloat(0.0)
continue
}
tmpv, e := strconv.ParseFloat(t.Field(i).Tag.Get("default"), 64)
if e != nil {
return fmt.Errorf("In field %s, default string can't be parse to float", fieldName)
}
v.Field(i).SetFloat(tmpv)
case reflect.Slice:
sl := &sliceValue{
typ:t.Field(i).Type.Elem(),
field:fieldName,
}
if e := sl.Set(raw); e != nil {
return e
}
v.Field(i).Set(sl.Vals)
default:
panic(fmt.Errorf("In field %s, unsupported type", fieldName))
}
}
return nil
}
func isDuration(typ reflect.Type) bool {
return typ == reflect.TypeOf(time.Duration(1))
}
func addMap(_struct interface{}, conf map[string]interface{}) error {
v, t := checkTypeAndPanic(_struct)
for i := 0; i < v.NumField(); i++ {
fieldName := t.Field(i).Name
if !v.Field(i).CanSet() {
continue
}
mv, ok := conf[fieldName]
if !ok {
continue
}
switch t.Field(i).Type.Kind() {
case reflect.String:
if reflect.TypeOf(mv).Kind() != reflect.String {
return fmt.Errorf("In field %s, the type not match, should be string", fieldName)
} else {
v.Field(i).SetString(mv.(string))
}
case reflect.Bool:
if reflect.TypeOf(mv).Kind() != reflect.Bool {
return fmt.Errorf("In field %s, the type not match, should be bool", fieldName)
} else {
v.Field(i).SetBool(mv.(bool))
}
case reflect.Int64, reflect.Int:
if isDuration(t.Field(i).Type) {
if reflect.TypeOf(mv).Kind() == reflect.String {
dur, err := time.ParseDuration(mv.(string))
if err != nil {
return fmt.Errorf("In field %s, Can't parse time duration in json: %s", fieldName, err.Error())
}
mv = dur
} else if reflect.TypeOf(mv).Kind() != reflect.Int64 {
return fmt.Errorf("In field %s, the type not match, should be number or time duration", fieldName)
}
}
if reflect.TypeOf(mv).ConvertibleTo(t.Field(i).Type) {
v.Field(i).Set(reflect.ValueOf(mv).Convert(t.Field(i).Type))
} else {
return fmt.Errorf("In field %s, the type not match, should be number", fieldName)
}
case reflect.Float64:
if reflect.TypeOf(mv).ConvertibleTo(t.Field(i).Type) {
v.Field(i).Set(reflect.ValueOf(mv).Convert(t.Field(i).Type))
} else {
return fmt.Errorf("In field %s, the type not match, should be number", fieldName)
}
case reflect.Slice:
if reflect.TypeOf(mv).Kind() != reflect.Slice {
return fmt.Errorf("In field %s, the type not match, should be slice", fieldName)
}
vm := reflect.ValueOf(mv)
tshould := t.Field(i).Type.Elem()
le := vm.Len()
tmpTransed := reflect.MakeSlice(reflect.SliceOf(tshould), le, le)
for i := 0; i < le; i++ {
if reflect.TypeOf(vm.Index(i).Interface()).ConvertibleTo(tshould) {
tmpTransed.Index(i).Set( reflect.ValueOf(vm.Index(i).Interface()).Convert(tshould) )
} else {
return fmt.Errorf("In field %s, have a Un Convertible value, at postion %d", fieldName, i)
}
}
v.Field(i).Set(tmpTransed)
default:
panic(fmt.Errorf("In field %s, unsupported type", fieldName))
}
}
return nil
}