-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.go
49 lines (44 loc) · 898 Bytes
/
watch.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
package config
import (
"log"
"github.com/fsnotify/fsnotify"
)
// Watcher 监听配置文件变化
func watcher(cfgChan chan *Config, path string) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
log.Println("event:", event)
if event.Op&fsnotify.Write == fsnotify.Write {
log.Println("配置文件发生变化")
cfg, err := readConfFile(path)
if err != nil {
log.Println("配置文件变化,但格式解析错误,忽略变更。错误:", err)
continue
}
cfgChan <- cfg
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
err = watcher.Add(path)
if err != nil {
log.Fatal(err)
}
<-done
}