-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
kami.go
79 lines (68 loc) · 1.85 KB
/
kami.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
77
78
79
// +build !go1.7
package kami
import (
"net/http"
"github.com/zenazn/goji/web/mutil"
"golang.org/x/net/context"
)
// kami is the heart of the package.
// It wraps a ContextHandler into an httprouter compatible request,
// in order to run all the middleware and other special handlers.
type kami struct {
handler ContextHandler
autocancel *bool
base *context.Context
middleware *wares
panicHandler *HandlerType
logHandler *func(context.Context, mutil.WriterProxy, *http.Request)
}
func (k kami) handle(w http.ResponseWriter, r *http.Request, params map[string]string) {
var (
ctx = defaultContext(*k.base, r)
autocancel = *k.autocancel
handler = k.handler
mw = *k.middleware
panicHandler = *k.panicHandler
logHandler = *k.logHandler
ranLogHandler = false // track this in case the log handler blows up
)
if len(params) > 0 {
ctx = newContextWithParams(ctx, params)
}
if autocancel {
var cancel context.CancelFunc
ctx, cancel = context.WithCancel(ctx)
defer cancel()
}
var proxy mutil.WriterProxy
if logHandler != nil || mw.needsWrapper() {
proxy = mutil.WrapWriter(w)
w = proxy
}
if panicHandler != nil {
defer func() {
if err := recover(); err != nil {
ctx = newContextWithException(ctx, err)
wrap(panicHandler).ServeHTTPContext(ctx, w, r)
if logHandler != nil && !ranLogHandler {
logHandler(ctx, proxy, r)
// should only happen if header hasn't been written
proxy.WriteHeader(http.StatusInternalServerError)
}
}
}()
}
ctx, ok := mw.run(ctx, w, r)
if ok {
handler.ServeHTTPContext(ctx, w, r)
}
if proxy != nil {
ctx = mw.after(ctx, proxy, r)
}
if logHandler != nil {
ranLogHandler = true
logHandler(ctx, proxy, r)
// should only happen if header hasn't been written
proxy.WriteHeader(http.StatusInternalServerError)
}
}