-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
63 lines (48 loc) · 1.07 KB
/
main.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
package gogenviper
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
"log"
)
type CfgFileWatcher[T any] struct {
viper *viper.Viper
model T
}
func Init[T any](path string, fileName string, fileType string, model T) (*CfgFileWatcher[T], error) {
v := viper.New()
v.AddConfigPath(path)
v.SetConfigName(fileName)
v.SetConfigType(fileType)
err := v.ReadInConfig()
if err != nil {
return nil, err
}
err = v.Unmarshal(model)
if err != nil {
return nil, err
}
return &CfgFileWatcher[T]{viper: v, model: model}, nil
}
func (w CfgFileWatcher[T]) refresh() error {
err := w.viper.ReadInConfig()
if err != nil {
return err
}
err = w.viper.Unmarshal(w.model)
if err != nil {
return err
}
return nil
}
func (w CfgFileWatcher[T]) Watch() {
w.viper.WatchConfig()
w.viper.OnConfigChange(func(in fsnotify.Event) {
err := w.refresh()
if err != nil {
log.Println("Error on refreshing application toggles due to file change, error: ", err)
return
}
log.Println(fmt.Sprintf("Application configuration %T file changed", w.model))
})
}