/
watch.go
75 lines (61 loc) · 1.15 KB
/
watch.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
package riff
import (
"sync"
)
type WatchType int
const (
NodeChanged WatchType = 1 << iota
ServiceChanged
)
func (w WatchType) String() string {
switch w {
case NodeChanged:
return "NodeChanged"
case ServiceChanged:
return "ServiceChanged"
default:
return "Unknow"
}
}
type WatchParam struct {
Name string `json:"name"`
WatchType `json:"watchType"`
}
type WatchHandler interface {
GetParam() *WatchParam
HandleWatch()
}
type Watch struct {
sync.Mutex
handlers map[WatchHandler]struct{}
}
func NewWatch() *Watch {
return &Watch{
handlers: make(map[WatchHandler]struct{}),
}
}
func (w *Watch) RegisterHandler(wh WatchHandler) {
w.Lock()
defer w.Unlock()
// Do nothing if already registered
if _, ok := w.handlers[wh]; ok {
return
}
// Register
w.handlers[wh] = struct{}{}
// Dispatch once
wh.HandleWatch()
}
func (w *Watch) DeregisterHandler(wh WatchHandler) {
w.Lock()
defer w.Unlock()
delete(w.handlers, wh)
}
func (w *Watch) Dispatch(param WatchParam) {
for wh := range w.handlers {
whParam := wh.GetParam()
if whParam.Name == param.Name && whParam.WatchType == param.WatchType {
wh.HandleWatch()
}
}
}