watcher.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package raftd
  2. import (
  3. "path"
  4. "strings"
  5. "fmt"
  6. )
  7. type Watcher struct {
  8. chanMap map[string][]chan int
  9. }
  10. func createWatcher() *Watcher {
  11. w := new(Watcher)
  12. w.chanMap = make(map[string][]chan int)
  13. return w
  14. }
  15. func (w *Watcher) add(prefix string, c chan int) error {
  16. prefix = path.Clean(prefix)
  17. fmt.Println("Add ", prefix)
  18. _, ok := w.chanMap[prefix]
  19. if !ok {
  20. w.chanMap[prefix] = make([]chan int, 0)
  21. w.chanMap[prefix] = append(w.chanMap[prefix], c)
  22. } else {
  23. w.chanMap[prefix] = append(w.chanMap[prefix], c)
  24. }
  25. fmt.Println(len(w.chanMap[prefix]), "@", prefix)
  26. go wait(c)
  27. return nil
  28. }
  29. func wait(c chan int) {
  30. result := <-c
  31. if result == 0 {
  32. fmt.Println("yes")
  33. } else {
  34. fmt.Println("no")
  35. }
  36. }
  37. func (w *Watcher) notify(action int, key string, oldValue string, newValue string) error {
  38. key = path.Clean(key)
  39. segments := strings.Split(key, "/")
  40. currPath := "/"
  41. for _, segment := range segments {
  42. currPath := path.Join(currPath, segment)
  43. fmt.Println(currPath)
  44. chans, ok := w.chanMap[currPath]
  45. if ok {
  46. fmt.Println("found ", currPath)
  47. for _, c := range chans {
  48. c <- 0
  49. }
  50. delete(w.chanMap, currPath)
  51. }
  52. }
  53. return nil
  54. }