...
1
16
17
21
22 package filesystem
23
24 import (
25 "github.com/fsnotify/fsnotify"
26 )
27
28
29 type FSWatcher interface {
30
31
32 Init(FSEventHandler, FSErrorHandler) error
33
34
35
36 Run()
37
38
39 AddWatch(path string) error
40 }
41
42
43 type FSEventHandler func(event fsnotify.Event)
44
45
46 type FSErrorHandler func(err error)
47
48 type fsnotifyWatcher struct {
49 watcher *fsnotify.Watcher
50 eventHandler FSEventHandler
51 errorHandler FSErrorHandler
52 }
53
54 var _ FSWatcher = &fsnotifyWatcher{}
55
56 func (w *fsnotifyWatcher) AddWatch(path string) error {
57 return w.watcher.Add(path)
58 }
59
60 func (w *fsnotifyWatcher) Init(eventHandler FSEventHandler, errorHandler FSErrorHandler) error {
61 var err error
62 w.watcher, err = fsnotify.NewWatcher()
63 if err != nil {
64 return err
65 }
66
67 w.eventHandler = eventHandler
68 w.errorHandler = errorHandler
69 return nil
70 }
71
72 func (w *fsnotifyWatcher) Run() {
73 go func() {
74 defer w.watcher.Close()
75 for {
76 select {
77 case event := <-w.watcher.Events:
78 if w.eventHandler != nil {
79 w.eventHandler(event)
80 }
81 case err := <-w.watcher.Errors:
82 if w.errorHandler != nil {
83 w.errorHandler(err)
84 }
85 }
86 }
87 }()
88 }
89
View as plain text