-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.go
73 lines (64 loc) · 1.27 KB
/
loader.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
package confutil
import (
"bytes"
"fmt"
"io/fs"
"os"
"dario.cat/mergo"
"gopkg.in/yaml.v3"
)
type Loader[C any] struct {
fs fs.FS
}
func NewLoader[C any](fs_ fs.FS) *Loader[C] {
return &Loader[C]{fs: fs_}
}
func (l *Loader[C]) Load(env Env) (*C, error) {
conf := map[string]interface{}{}
c, err := l.loadYAML("config.yaml")
if err != nil {
return nil, err
}
mergo.Merge(&conf, &c, mergo.WithOverride)
paths := []string{
"config.local.yaml",
fmt.Sprintf("config.%s.yaml", env),
fmt.Sprintf("config.%s.local.yaml", env),
}
for _, p := range paths {
c, err := l.loadYAML(p)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
mergo.Merge(&conf, &c, mergo.WithOverride)
}
result := new(C)
tmp, err := yaml.Marshal(conf)
if err != nil {
return nil, err
}
err = yaml.Unmarshal(tmp, result)
if err != nil {
return nil, err
}
return result, nil
}
func (l *Loader[C]) loadYAML(path string) (map[string]interface{}, error) {
f, err := l.fs.Open(path)
if err != nil {
return nil, err
}
w := bytes.NewBuffer([]byte{})
name := "main"
t := NewYAMLTemplate()
err = t.Compile(name, f, w)
if err != nil {
return nil, err
}
c := map[string]interface{}{}
err = yaml.Unmarshal(w.Bytes(), &c)
if err != nil {
return nil, err
}
return c, nil
}