-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
kami_17.go
84 lines (72 loc) · 1.92 KB
/
kami_17.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
80
81
82
83
84
// +build go1.7
package kami
import (
"context"
"net/http"
"github.com/zenazn/goji/web/mutil"
)
// 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()
}
if ctx != context.Background() {
r = r.WithContext(ctx)
}
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)
r = r.WithContext(ctx)
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)
}
}
}()
}
r, ctx, ok := mw.run(ctx, w, r)
if ok {
handler.ServeHTTPContext(ctx, w, r)
}
if proxy != nil {
r, 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)
}
}