This repository has been archived by the owner on Jun 13, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfile_watcher.go
118 lines (100 loc) · 2.16 KB
/
file_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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package confl
import (
"encoding/json"
"io/ioutil"
"reflect"
"sync"
"github.com/fsnotify/fsnotify"
)
// Unmarshal - unmarshal function for FileWatcher
type Unmarshal func([]byte, interface{}) error
// fileWatcher watch the changes of configuration file
type fileWatcher struct {
confPath string
c interface{}
oCopyed interface{}
nCopyL sync.RWMutex
nCopyed interface{}
w *fsnotify.Watcher
hookL sync.Mutex
hooks []Hook
errHandle func(error)
unmarshal Unmarshal
}
// NewFileWatcher returns new a Watcher for file system
func NewFileWatcher(c interface{}, confPath string, fns ...Unmarshal) (Watcher, error) {
unmarshal := json.Unmarshal
if len(fns) > 0 {
unmarshal = fns[0]
}
f := &fileWatcher{
confPath: confPath,
c: c,
hooks: []Hook{},
errHandle: defautlOnError,
unmarshal: unmarshal,
}
var err error
if f.w, err = fsnotify.NewWatcher(); err != nil {
return nil, err
}
if err = f.w.Add(confPath); err != nil {
return nil, err
}
if err = f.loadConfig(); err != nil {
return nil, err
}
return f, nil
}
func (f *fileWatcher) loadConfig() error {
fileData, err := ioutil.ReadFile(f.confPath)
if err != nil {
return err
}
fc := reflect.New(reflect.TypeOf(f.c).Elem()).Interface()
if err = f.unmarshal(fileData, fc); err != nil {
return err
}
f.oCopyed = f.nCopyed
// w.c must be ptr type
i := reflect.Indirect(reflect.ValueOf(fc)).Interface()
f.nCopyL.Lock()
f.nCopyed = i
f.nCopyL.Unlock()
return nil
}
func (f *fileWatcher) Config() interface{} {
f.nCopyL.RLock()
defer f.nCopyL.RUnlock()
return f.nCopyed
}
func (f *fileWatcher) Watch() {
for {
select {
case ev := <-f.w.Events:
if ev.Op != fsnotify.Write {
continue
}
if err := f.loadConfig(); err != nil {
f.errHandle(err)
continue
}
for _, hook := range f.hooks {
hook(f.oCopyed, f.Config())
}
case err := <-f.w.Errors:
f.errHandle(err)
}
}
}
func (f *fileWatcher) AddHook(h ...Hook) {
f.hookL.Lock()
f.hooks = append(f.hooks, h...)
f.hookL.Unlock()
}
func (f *fileWatcher) OnError(h func(error)) {
f.errHandle = h
}
func (f *fileWatcher) Close() error {
return f.w.Close()
}