watch_key_handler.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package v1
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "strconv"
  6. etcdErr "github.com/coreos/etcd/error"
  7. "github.com/coreos/etcd/third_party/github.com/gorilla/mux"
  8. )
  9. // Watches a given key prefix for changes.
  10. func WatchKeyHandler(w http.ResponseWriter, req *http.Request, s Server) error {
  11. var err error
  12. vars := mux.Vars(req)
  13. key := "/" + vars["key"]
  14. // Create a command to watch from a given index (default 0).
  15. var sinceIndex uint64 = 0
  16. if req.Method == "POST" {
  17. sinceIndex, err = strconv.ParseUint(string(req.FormValue("index")), 10, 64)
  18. if err != nil {
  19. return etcdErr.NewError(203, "Watch From Index", s.Store().Index())
  20. }
  21. }
  22. // Start the watcher on the store.
  23. watcher, err := s.Store().Watch(key, false, false, sinceIndex)
  24. if err != nil {
  25. return etcdErr.NewError(500, key, s.Store().Index())
  26. }
  27. event := <-watcher.EventChan
  28. // Convert event to a response and write to client.
  29. w.WriteHeader(http.StatusOK)
  30. if req.Method == "HEAD" {
  31. return nil
  32. }
  33. b, _ := json.Marshal(event.Response(s.Store().Index()))
  34. w.Write(b)
  35. return nil
  36. }