-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloadConfig.go
More file actions
69 lines (58 loc) · 1.44 KB
/
loadConfig.go
File metadata and controls
69 lines (58 loc) · 1.44 KB
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
package loadConfig
import (
"fmt"
"reflect"
"github.com/spf13/viper"
)
func LoadConfigWithEnvEntry(c interface{}, v *viper.Viper, entryName string) {
if err := isPtrToStruct(c); err != nil {
panic(err)
}
container := reflect.ValueOf(c).Elem()
setValue(container, v, entryName)
}
func LoadConfig(c interface{}, v *viper.Viper) {
LoadConfigWithEnvEntry(c, v, "")
}
func setValue(container reflect.Value, v *viper.Viper, lastTag string) {
for j := 0; j < container.NumField(); j++ {
fieldType := container.Type().Field(j)
fieldName := fieldType.Name
f := container.Field(j)
newTag := string(fieldType.Tag.Get("cfg"))
if newTag == "" && f.Type().Kind() != reflect.Struct {
// tage shouldn't be empty unless it's struct
panic(fmt.Sprintf("tag not set for %s", fieldName))
}
if newTag == "-" {
continue
}
if !f.IsValid() || !f.CanSet() {
panic(fmt.Sprintf("can't set field %s", fieldName))
}
tag := combineTage(lastTag, newTag)
noValue := func() {
panic(fmt.Sprintf("can't get config for %s", tag))
}
switch f.Type().Kind() {
case reflect.String:
value := v.GetString(tag)
if value == "" {
noValue()
}
f.SetString(value)
case reflect.Int:
value := int64(v.GetInt(tag))
if value == 0 {
noValue()
}
f.SetInt(int64(v.GetInt(tag)))
case reflect.Struct:
if newTag != "-" {
setValue(f, v, tag)
}
default:
panic(fmt.Sprintf("can't handle %s", f.Type().String()))
}
}
}