handler.go 1.3 KB

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