get_handler.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package v2
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "strconv"
  8. etcdErr "github.com/coreos/etcd/error"
  9. "github.com/coreos/etcd/log"
  10. "github.com/coreos/etcd/store"
  11. "github.com/coreos/raft"
  12. "github.com/gorilla/mux"
  13. )
  14. func GetHandler(w http.ResponseWriter, req *http.Request, s Server) error {
  15. var err error
  16. var event *store.Event
  17. vars := mux.Vars(req)
  18. key := "/" + vars["key"]
  19. // Help client to redirect the request to the current leader
  20. if req.FormValue("consistent") == "true" && s.State() != raft.Leader {
  21. leader := s.Leader()
  22. hostname, _ := s.ClientURL(leader)
  23. url, err := url.Parse(hostname)
  24. if err != nil {
  25. log.Warn("Redirect cannot parse hostName ", hostname)
  26. return err
  27. }
  28. url.RawQuery = req.URL.RawQuery
  29. url.Path = req.URL.Path
  30. log.Debugf("Redirect consistent get to %s", url.String())
  31. http.Redirect(w, req, url.String(), http.StatusTemporaryRedirect)
  32. return nil
  33. }
  34. recursive := (req.FormValue("recursive") == "true")
  35. sorted := (req.FormValue("sorted") == "true")
  36. if req.FormValue("wait") == "true" { // watch
  37. // Create a command to watch from a given index (default 0).
  38. var sinceIndex uint64 = 0
  39. waitIndex := req.FormValue("waitIndex")
  40. if waitIndex != "" {
  41. sinceIndex, err = strconv.ParseUint(string(req.FormValue("waitIndex")), 10, 64)
  42. if err != nil {
  43. return etcdErr.NewError(etcdErr.EcodeIndexNaN, "Watch From Index", s.Store().Index())
  44. }
  45. }
  46. // Start the watcher on the store.
  47. watcher, err := s.Store().Watch(key, recursive, sinceIndex)
  48. if err != nil {
  49. return err
  50. }
  51. cn, _ := w.(http.CloseNotifier)
  52. closeChan := cn.CloseNotify()
  53. select {
  54. case <-closeChan:
  55. watcher.Remove()
  56. return nil
  57. case event = <-watcher.EventChan:
  58. }
  59. } else { //get
  60. // Retrieve the key from the store.
  61. event, err = s.Store().Get(key, recursive, sorted)
  62. if err != nil {
  63. return err
  64. }
  65. }
  66. w.Header().Set("Content-Type", "application/json")
  67. w.Header().Add("X-Etcd-Index", fmt.Sprint(s.Store().Index()))
  68. w.Header().Add("X-Raft-Index", fmt.Sprint(s.CommitIndex()))
  69. w.Header().Add("X-Raft-Term", fmt.Sprint(s.Term()))
  70. w.WriteHeader(http.StatusOK)
  71. b, _ := json.Marshal(event)
  72. w.Write(b)
  73. return nil
  74. }