-
Notifications
You must be signed in to change notification settings - Fork 12
/
reflect.go
79 lines (66 loc) · 1.59 KB
/
reflect.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
package conf
import (
"errors"
"fmt"
"reflect"
"github.com/spf13/viper"
)
const tagPrefix = "viper"
func populateConfig(config *Config) (*Config, error) {
err := recursivelySet(reflect.ValueOf(config), "")
if err != nil {
return nil, err
}
return config, nil
}
func recursivelySet(val reflect.Value, prefix string) error {
if val.Kind() != reflect.Ptr {
return errors.New("WTF")
}
// dereference
val = reflect.Indirect(val)
if val.Kind() != reflect.Struct {
return errors.New("FML")
}
// grab the type for this instance
vType := reflect.TypeOf(val.Interface())
// go through child fields
for i := 0; i < val.NumField(); i++ {
thisField := val.Field(i)
thisType := vType.Field(i)
tag := prefix + getTag(thisType)
switch thisField.Kind() {
case reflect.Struct:
if err := recursivelySet(thisField.Addr(), tag+"."); err != nil {
return err
}
case reflect.Int:
fallthrough
case reflect.Int32:
fallthrough
case reflect.Int64:
// you can only set with an int64 -> int
configVal := int64(viper.GetInt(tag))
thisField.SetInt(configVal)
case reflect.String:
thisField.SetString(viper.GetString(tag))
case reflect.Bool:
thisField.SetBool(viper.GetBool(tag))
default:
return fmt.Errorf("unexpected type detected ~ aborting: %s", thisField.Kind())
}
}
return nil
}
func getTag(field reflect.StructField) string {
// check if maybe we have a special magic tag
tag := field.Tag
if tag != "" {
for _, prefix := range []string{tagPrefix, "mapstructure", "json"} {
if v := tag.Get(prefix); v != "" {
return v
}
}
}
return field.Name
}