handler.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package v2
  2. import (
  3. "net/http"
  4. "github.com/gorilla/mux"
  5. etcdErr "github.com/coreos/etcd/error"
  6. )
  7. // prefix is appended to the lock's prefix since the leader mod uses the lock mod.
  8. const prefix = "/_mod/leader"
  9. // handler manages the leader HTTP request.
  10. type handler struct {
  11. *mux.Router
  12. client *http.Client
  13. transport *http.Transport
  14. addr string
  15. }
  16. // NewHandler creates an HTTP handler that can be registered on a router.
  17. func NewHandler(addr string) (http.Handler) {
  18. transport := &http.Transport{DisableKeepAlives: false}
  19. h := &handler{
  20. Router: mux.NewRouter(),
  21. client: &http.Client{Transport: transport},
  22. transport: transport,
  23. addr: addr,
  24. }
  25. h.StrictSlash(false)
  26. h.handleFunc("/{key:.*}", h.getHandler).Methods("GET")
  27. h.handleFunc("/{key:.*}", h.setHandler).Methods("PUT")
  28. h.handleFunc("/{key:.*}", h.deleteHandler).Methods("DELETE")
  29. return h
  30. }
  31. func (h *handler) handleFunc(path string, f func(http.ResponseWriter, *http.Request) error) *mux.Route {
  32. return h.Router.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {
  33. if err := f(w, req); err != nil {
  34. switch err := err.(type) {
  35. case *etcdErr.Error:
  36. w.Header().Set("Content-Type", "application/json")
  37. err.Write(w)
  38. default:
  39. http.Error(w, err.Error(), http.StatusInternalServerError)
  40. }
  41. }
  42. })
  43. }