-
Notifications
You must be signed in to change notification settings - Fork 329
/
watcher.go
97 lines (88 loc) · 1.74 KB
/
watcher.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
package config
import (
"errors"
"strings"
"sync"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
const (
CFG_SUFFIX = "toml"
)
type ConfigWatcher struct {
FuncConfigParse FuncConfigParse
watcher *fsnotify.Watcher
stopSignal chan bool
wg sync.WaitGroup
err error
}
func (cw *ConfigWatcher) Error() error {
return cw.err
}
func (cw *ConfigWatcher) Stop() {
cw.stopSignal <- true
close(cw.stopSignal)
cw.wg.Wait()
cw.watcher.Close()
}
func (cw *ConfigWatcher) Watch(dir string) {
mask := fsnotify.Write | fsnotify.Create
cw.wg.Add(1)
go func() {
defer cw.wg.Done()
for {
select {
case event, ok := <-cw.watcher.Events:
if !ok {
cw.err = errors.New("failed to read watcher events.")
return
}
if event.Op&mask != 0 {
// got we need.
if strings.HasSuffix(event.Name, CFG_SUFFIX) {
viper.SetConfigFile(event.Name)
err := viper.ReadInConfig()
if err != nil {
cw.err = err
return
}
cfg := &Config{}
err = cfg.Parse()
if err != nil {
cw.err = err
return
}
err = cw.FuncConfigParse(cfg)
if err != nil {
cw.err = err
return
}
}
}
case err := <-cw.watcher.Errors:
if err != nil {
cw.err = err
return
}
case stopped := <-cw.stopSignal:
if stopped {
cw.err = nil
return
}
}
}
}()
}
func NewConfigWatcher(funcConfigParse FuncConfigParse) (*ConfigWatcher, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
cw := &ConfigWatcher{
FuncConfigParse: funcConfigParse,
watcher: watcher,
stopSignal: make(chan bool),
err: nil,
}
return cw, nil
}