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