-
Notifications
You must be signed in to change notification settings - Fork 1
/
monitor.go
64 lines (56 loc) · 976 Bytes
/
monitor.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
package monitor
import (
"errors"
"sync"
"time"
)
type (
Monitor interface {
AddFile(path string, spec string, handler func()) error
DelFile(path string) error
}
myMonitor struct {
sync.RWMutex
fs Files
}
Files map[string]*myFile
)
func (m *myMonitor) init() {
m.fs = make(map[string]*myFile)
}
func NewMonitor() Monitor {
mon := new(myMonitor)
mon.init()
return mon
}
func (m *myMonitor) AddFile(path string, spec string, handler func()) error {
m.Lock()
defer m.Unlock()
if handler == nil {
return errors.New("handler cannot be nil")
}
if _, ok := m.fs[path]; ok {
return errors.New("already exist")
}
f := &myFile{
spec: spec,
filePath: path,
updateOn: time.Now().Unix(),
handle: handler,
}
m.fs[path] = f
f.init()
return nil
}
func (m *myMonitor) DelFile(path string) error {
m.Lock()
defer m.Unlock()
f, ok := m.fs[path]
if !ok {
return nil
}
f.c.Stop()
f.c.Remove(f.id)
delete(m.fs, path)
return nil
}