-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
51 lines (43 loc) · 1011 Bytes
/
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
package webserver
import (
"log"
"os"
"time"
cache "github.com/patrickmn/go-cache"
"github.com/rjeczalik/notify"
)
var WatcherNotifies = []notify.Event{notify.All}
func NewFileWatcher(path string, fn func(ev string, path string)) {
go func() {
c := make(chan notify.EventInfo, 1)
err := notify.Watch(path+"/...", c, WatcherNotifies...)
if err != nil {
log.Fatal(err)
}
defer notify.Stop(c)
timeCache := cache.New(5*time.Minute, 30*time.Second)
for {
// Block until an event is received.
ei := <-c
eventPath := ei.Path()
st, err := os.Stat(eventPath)
if err != nil {
timeCache.Delete(eventPath)
continue
}
modTime := st.ModTime()
isEnable := true
if v, has := timeCache.Get(eventPath); has {
if oldTime, is := v.(time.Time); is {
if oldTime.Equal(modTime) {
isEnable = false
}
}
}
if isEnable {
fn(ei.Event().String()[7:], eventPath)
}
timeCache.Set(eventPath, modTime, cache.DefaultExpiration)
}
}()
}