-
Notifications
You must be signed in to change notification settings - Fork 0
/
reloader.go
44 lines (40 loc) · 897 Bytes
/
reloader.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
package reloader
import (
"fmt"
"time"
"github.com/fsnotify/fsnotify"
)
func Watch(dir string, load func(), delay time.Duration) error {
return watch(fsnotify.NewWatcher, dir, load, delay)
}
func watch(fn func() (*fsnotify.Watcher, error), dir string, load func(), delay time.Duration) error {
watcher, err := fn()
if err != nil {
return fmt.Errorf("unable to initialize file system notifications: %v", err)
}
if err := watcher.Add(dir); err != nil {
return fmt.Errorf("unable to watch directory: %v", err)
}
go func() {
var cancel chan struct{}
for {
select {
case e := <-watcher.Events:
if e.Op != 0 {
if cancel != nil {
close(cancel)
}
cancel = make(chan struct{})
go func(cancel chan struct{}) {
select {
case <-time.After(delay):
load()
case <-cancel:
}
}(cancel)
}
}
}
}()
return nil
}