forked from VividCortex/siesta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
76 lines (61 loc) · 1.95 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package siesta
import (
"errors"
"net/http"
)
var ErrUnsupportedHandler = errors.New("siesta: unsupported handler")
type contextHandler func(Context, http.ResponseWriter, *http.Request, func())
func (h contextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h(emptyContext{}, w, r, nil)
}
func (h contextHandler) ServeHTTPInContext(c Context, w http.ResponseWriter, r *http.Request) {
h(c, w, r, nil)
}
func toContextHandler(f interface{}) contextHandler {
var m contextHandler
switch f.(type) {
case func(Context, http.ResponseWriter, *http.Request, func()):
m = contextHandler(f.(func(Context, http.ResponseWriter, *http.Request, func())))
case contextHandler:
m = f.(contextHandler)
case func(Context, http.ResponseWriter, *http.Request):
m = func(c Context, w http.ResponseWriter, r *http.Request, q func()) {
f.(func(Context, http.ResponseWriter, *http.Request))(c, w, r)
}
case func(http.ResponseWriter, *http.Request, func()):
m = func(c Context, w http.ResponseWriter, r *http.Request, q func()) {
f.(func(http.ResponseWriter, *http.Request, func()))(w, r, q)
}
case func(http.ResponseWriter, *http.Request):
m = func(c Context, w http.ResponseWriter, r *http.Request, q func()) {
f.(func(http.ResponseWriter, *http.Request))(w, r)
}
default:
// Check for http.Handlers too.
if h, ok := f.(http.Handler); ok {
return toContextHandler(h.ServeHTTP)
}
panic(ErrUnsupportedHandler)
}
return m
}
// Compose composes multiple contextHandlers into a single contextHandler.
func Compose(stack ...interface{}) contextHandler {
contextStack := make([]contextHandler, 0, len(stack))
for i := range stack {
m := toContextHandler(stack[i])
contextStack = append(contextStack, m)
}
return func(c Context, w http.ResponseWriter, r *http.Request, quit func()) {
quitStack := false
for _, m := range contextStack {
m(c, w, r, func() {
quitStack = true
})
if quitStack {
quit()
break
}
}
}
}