-
Notifications
You must be signed in to change notification settings - Fork 5
/
watcher.go
71 lines (59 loc) · 1.19 KB
/
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package consul
import (
"github.com/go-kratos/kratos/v2/config"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/api/watch"
)
type watcher struct {
source *source
ch chan interface{}
closeChan chan struct{}
wp *watch.Plan
}
func (w *watcher) handle(idx uint64, data interface{}) {
if data == nil {
return
}
_, ok := data.(api.KVPairs)
if !ok {
return
}
w.ch <- struct{}{}
}
func newWatcher(s *source) (*watcher, error) {
w := &watcher{
source: s,
ch: make(chan interface{}),
closeChan: make(chan struct{}),
}
wp, err := watch.Parse(map[string]interface{}{"type": "keyprefix", "prefix": s.options.path})
if err != nil {
return nil, err
}
wp.Handler = w.handle
w.wp = wp
// wp.Run is a blocking call and will prevent newWatcher from returning
go func() {
err := wp.RunWithClientAndHclog(s.client, nil)
if err != nil {
panic(err)
}
}()
return w, nil
}
func (w *watcher) Next() ([]*config.KeyValue, error) {
select {
case _, ok := <-w.ch:
if !ok {
return nil, nil
}
return w.source.Load()
case <-w.closeChan:
return nil, nil
}
}
func (w *watcher) Stop() error {
w.wp.Stop()
close(w.closeChan)
return nil
}