-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
58 lines (49 loc) · 1.45 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
package config
import (
"github.com/fsnotify/fsnotify"
"github.com/gowins/dionysus/log"
"github.com/spf13/viper"
)
var (
DefaultFilePath = "./etc/"
DefaultConfigName = "config"
)
type WatchHandler func(string) error
type WatchConfigHandler struct {
Key string
OldValue string
Func WatchHandler
}
var watchConfigHandlers = []*WatchConfigHandler{}
func Setup(configHandlers ...*WatchConfigHandler) {
watchConfigHandlers = append(watchConfigHandlers, configHandlers...)
viper.SetConfigName(DefaultConfigName)
viper.SetConfigType("yaml")
viper.AddConfigPath(DefaultFilePath)
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("fatal error config file: %w", err)
}
for _, watchConfigHandler := range watchConfigHandlers {
watchConfigHandler.OldValue = viper.GetString(watchConfigHandler.Key)
}
viper.OnConfigChange(runHandler)
viper.WatchConfig()
}
func runHandler(in fsnotify.Event) {
defer func() {
if r := recover(); r != nil {
log.Errorf("Recovered from config handler. Err:%v ", r)
}
}()
for _, watchConfigHandler := range watchConfigHandlers {
newValue := viper.GetString(watchConfigHandler.Key)
if watchConfigHandler.OldValue != newValue {
watchConfigHandler.OldValue = newValue
if err := watchConfigHandler.Func(newValue); err != nil {
log.Errorf("handler key %v change error %v", watchConfigHandler.Key, err)
} else {
log.Infof("key %v change config handler success", watchConfigHandler.Key)
}
}
}
}