mirror of
https://github.com/etcd-io/etcd.git
synced 2024-09-27 06:25:44 +00:00
add basic watch implementation
This commit is contained in:
parent
20ca21a3f7
commit
1f57788f16
66
watcher.go
Normal file
66
watcher.go
Normal file
@ -0,0 +1,66 @@
|
||||
package raftd
|
||||
|
||||
import (
|
||||
"path"
|
||||
"strings"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Watcher struct {
|
||||
chanMap map[string][]chan int
|
||||
}
|
||||
|
||||
func createWatcher() *Watcher {
|
||||
w := new(Watcher)
|
||||
w.chanMap = make(map[string][]chan int)
|
||||
return w
|
||||
}
|
||||
|
||||
func (w *Watcher) add(prefix string, c chan int) error {
|
||||
|
||||
prefix = path.Clean(prefix)
|
||||
fmt.Println("Add ", prefix)
|
||||
_, ok := w.chanMap[prefix]
|
||||
if !ok {
|
||||
w.chanMap[prefix] = make([]chan int, 0)
|
||||
w.chanMap[prefix] = append(w.chanMap[prefix], c)
|
||||
} else {
|
||||
w.chanMap[prefix] = append(w.chanMap[prefix], c)
|
||||
}
|
||||
fmt.Println(len(w.chanMap[prefix]), "@", prefix)
|
||||
go wait(c)
|
||||
return nil
|
||||
}
|
||||
|
||||
func wait(c chan int) {
|
||||
result := <-c
|
||||
|
||||
if result == 0 {
|
||||
fmt.Println("yes")
|
||||
} else {
|
||||
fmt.Println("no")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (w *Watcher) notify(action int, key string, oldValue string, newValue string) error {
|
||||
key = path.Clean(key)
|
||||
|
||||
segments := strings.Split(key, "/")
|
||||
|
||||
currPath := "/"
|
||||
|
||||
for _, segment := range segments {
|
||||
currPath := path.Join(currPath, segment)
|
||||
fmt.Println(currPath)
|
||||
chans, ok := w.chanMap[currPath]
|
||||
if ok {
|
||||
fmt.Println("found ", currPath)
|
||||
for _, c := range chans {
|
||||
c <- 0
|
||||
}
|
||||
delete(w.chanMap, currPath)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
14
watcher_test.go
Normal file
14
watcher_test.go
Normal file
@ -0,0 +1,14 @@
|
||||
package raftd
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWatch(t *testing.T) {
|
||||
watcher := createWatcher()
|
||||
c := make(chan int)
|
||||
d := make(chan int)
|
||||
watcher.add("/prefix/", c)
|
||||
watcher.add("/prefix/", d)
|
||||
watcher.notify(0, "/prefix/hihihi", "1", "1")
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user