-
Notifications
You must be signed in to change notification settings - Fork 0
/
tinyviper.go
113 lines (104 loc) · 2.48 KB
/
tinyviper.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
package tinyviper
import (
"bufio"
"errors"
"os"
"reflect"
"strings"
)
type Resolver interface {
Get(key string) string
}
type EnvResolver struct{}
type EnvFileResolver struct {
Variables map[string]string
}
func (e EnvFileResolver) Get(key string) string {
return e.Variables[key]
}
func (e EnvResolver) Get(key string) string {
return os.Getenv(key)
}
type multiResolver struct {
resolvers []Resolver
}
func NewEnvResolver() Resolver {
return EnvResolver{}
}
func NewEnvFileResolver(filename string) Resolver {
readFile, err := os.Open(filename)
if err != nil {
return EnvFileResolver{make(map[string]string)}
}
defer readFile.Close()
r := EnvFileResolver{make(map[string]string, 0)}
fileScanner := bufio.NewScanner(readFile)
fileScanner.Split(bufio.ScanLines)
for fileScanner.Scan() {
text := fileScanner.Text()
index := strings.Index(text, "=")
if index == -1 || strings.HasPrefix(text, "#") {
continue
}
r.Variables[text[0:index]] = strings.Trim(text[index+1:], " \"'")
}
return r
}
func (m multiResolver) Get(key string) string {
for _, r := range m.resolvers {
if r == nil {
continue
}
v := r.Get(key)
if r.Get(key) != "" {
return v
}
}
return ""
}
func LoadFromResolver[T any](cfg *T, resolver ...Resolver) error {
res := multiResolver{resolvers: resolver}
missing := make([]string, 0)
missing, err := refelectStruct(cfg, res, missing)
if err != nil {
return err
}
if len(missing) > 0 {
return errors.New("missing config variables: " + strings.Join(missing, ","))
}
return nil
}
func refelectStruct(object any, resolver Resolver, missing []string) ([]string, error) {
v := reflect.ValueOf(object)
if v.Elem().Kind() != reflect.Struct {
return missing, errors.New("type must be a struct")
}
e := v.Elem()
t := e.Type()
for i := 0; i < t.NumField(); i++ {
ef := e.Field(i)
tf := t.Field(i)
envName := tf.Tag.Get("env")
if envName != "" {
if tf.Type != reflect.TypeOf("") {
return missing, errors.New("env annotated field must have type string")
}
if !ef.CanSet() {
return missing, errors.New("env field must be public")
}
value := resolver.Get(envName)
if value != "" {
ef.SetString(resolver.Get(envName))
} else if ef.String() == "" {
missing = append(missing, envName)
}
} else if t.Kind() == reflect.Struct {
m, err := refelectStruct(ef.Addr().Interface(), resolver, missing)
if err != nil {
return missing, err
}
missing = append(missing, m...)
}
}
return missing, nil
}