set_handler.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package v2
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/url"
  7. etcdErr "github.com/coreos/etcd/error"
  8. "github.com/coreos/etcd/third_party/github.com/gorilla/mux"
  9. )
  10. // setHandler attempts to set the current leader.
  11. func (h *handler) setHandler(w http.ResponseWriter, req *http.Request) error {
  12. vars := mux.Vars(req)
  13. name := req.FormValue("name")
  14. if name == "" {
  15. return etcdErr.NewError(etcdErr.EcodeNameRequired, "Set", 0)
  16. }
  17. // Proxy the request to the the lock service.
  18. u, err := url.Parse(fmt.Sprintf("%s/mod/v2/lock/%s", h.addr, vars["key"]))
  19. if err != nil {
  20. return err
  21. }
  22. q := u.Query()
  23. q.Set("value", name)
  24. q.Set("ttl", req.FormValue("ttl"))
  25. q.Set("timeout", req.FormValue("timeout"))
  26. u.RawQuery = q.Encode()
  27. r, err := http.NewRequest("POST", u.String(), nil)
  28. if err != nil {
  29. return err
  30. }
  31. // Close request if this connection disconnects.
  32. closeNotifier, _ := w.(http.CloseNotifier)
  33. stopChan := make(chan bool)
  34. defer close(stopChan)
  35. go func() {
  36. select {
  37. case <-closeNotifier.CloseNotify():
  38. h.transport.CancelRequest(r)
  39. case <-stopChan:
  40. }
  41. }()
  42. // Read from the leader lock.
  43. resp, err := h.client.Do(r)
  44. if err != nil {
  45. return err
  46. }
  47. defer resp.Body.Close()
  48. w.WriteHeader(resp.StatusCode)
  49. io.Copy(w, resp.Body)
  50. return nil
  51. }