watch_key_handler.go 976 B

12345678910111213141516171819202122232425262728293031323334353637383940
  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/store"
  8. "github.com/gorilla/mux"
  9. )
  10. // Watches a given key prefix for changes.
  11. func WatchKeyHandler(w http.ResponseWriter, req *http.Request, s Server) error {
  12. var err error
  13. vars := mux.Vars(req)
  14. key := "/" + vars["key"]
  15. // Create a command to watch from a given index (default 0).
  16. var sinceIndex uint64 = 0
  17. if req.Method == "POST" {
  18. sinceIndex, err = strconv.ParseUint(string(req.FormValue("index")), 10, 64)
  19. if err != nil {
  20. return etcdErr.NewError(203, "Watch From Index", store.UndefIndex, store.UndefTerm)
  21. }
  22. }
  23. // Start the watcher on the store.
  24. c, err := s.Store().Watch(key, false, sinceIndex, s.CommitIndex(), s.Term())
  25. if err != nil {
  26. return etcdErr.NewError(500, key, store.UndefIndex, store.UndefTerm)
  27. }
  28. event := <-c
  29. b, _ := json.Marshal(event.Response())
  30. w.WriteHeader(http.StatusOK)
  31. w.Write(b)
  32. return nil
  33. }