From 1f57788f161d4508b0a2ce56494a08e14558f661 Mon Sep 17 00:00:00 2001 From: Xiang Li Date: Fri, 7 Jun 2013 10:45:33 -0700 Subject: [PATCH] add basic watch implementation --- watcher.go | 66 +++++++++++++++++++++++++++++++++++++++++++++++++ watcher_test.go | 14 +++++++++++ 2 files changed, 80 insertions(+) create mode 100644 watcher.go create mode 100644 watcher_test.go diff --git a/watcher.go b/watcher.go new file mode 100644 index 000000000..3760ec401 --- /dev/null +++ b/watcher.go @@ -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 +} \ No newline at end of file diff --git a/watcher_test.go b/watcher_test.go new file mode 100644 index 000000000..5a2f1b6dc --- /dev/null +++ b/watcher_test.go @@ -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") +} \ No newline at end of file