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