-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
66 lines (53 loc) · 1.23 KB
/
config.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
package starter
import (
"errors"
"fmt"
"log"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
var ErrConfigNotProvided = errors.New("config not provided")
type ConfigInit interface {
Prepare() error
}
func (s *Starter) Configure(confFile string, watchConf func(c interface{})) (interface{}, error) {
vip := viper.New()
if confFile != "" {
vip.SetConfigFile(confFile)
} else if len(s.confInits) > 0 {
for _, init := range s.confInits {
if err := init(vip); err != nil {
return nil, fmt.Errorf("config init: %w", err)
}
}
} else {
return nil, ErrConfigNotProvided
}
vip.AutomaticEnv()
if err := vip.ReadInConfig(); err != nil {
return nil, fmt.Errorf("read config: %w", err)
}
decoder := func() (interface{}, error) {
cfg, err := s.conf(vip)
if err != nil {
return nil, err
}
if ci, is := cfg.(ConfigInit); is {
if err := ci.Prepare(); err != nil {
return nil, fmt.Errorf("config prepare: %w", err)
}
}
return cfg, nil
}
if watchConf != nil {
vip.WatchConfig()
vip.OnConfigChange(func(_ fsnotify.Event) {
if conf, err := decoder(); err == nil {
watchConf(conf)
} else {
log.Printf("[starter] error while decoding conf %v\n", err)
}
})
}
return decoder()
}