github.com/ghodss/etcd@v0.3.1-0.20140417172404-cc329bfa55cb/mod/lock/v2/handler.go (about)

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