forked from guregu/kami
/
kami.go
216 lines (186 loc) · 5.64 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package kami
import (
"net/http"
"github.com/dimfeld/httptreemux"
"github.com/zenazn/goji/web/mutil"
"golang.org/x/net/context"
)
var (
// Context is the root "god object" from which every request's context will derive.
Context = context.Background()
// PanicHandler will, if set, be called on panics.
// You can use kami.Exception(ctx) within the panic handler to get panic details.
PanicHandler HandlerType
// LogHandler will, if set, wrap every request and be called at the very end.
LogHandler func(context.Context, mutil.WriterProxy, *http.Request)
)
var (
routes = newRouter()
enable405 = true
)
func init() {
// set up the default 404/405 handlers
NotFound(nil)
MethodNotAllowed(nil)
}
func newRouter() *httptreemux.TreeMux {
r := httptreemux.New()
r.PathSource = httptreemux.URLPath
r.RedirectBehavior = httptreemux.Redirect307
r.RedirectMethodBehavior = map[string]httptreemux.RedirectBehavior{
"GET": httptreemux.Redirect301,
}
return r
}
// Handler returns an http.Handler serving registered routes.
func Handler() http.Handler {
return routes
}
// Handle registers an arbitrary method handler under the given path.
func Handle(method, path string, handler HandlerType) {
routes.Handle(method, path, bless(wrap(handler)))
}
// Get registers a GET handler under the given path.
func Get(path string, handler HandlerType) {
Handle("GET", path, handler)
}
// Post registers a POST handler under the given path.
func Post(path string, handler HandlerType) {
Handle("POST", path, handler)
}
// Put registers a PUT handler under the given path.
func Put(path string, handler HandlerType) {
Handle("PUT", path, handler)
}
// Patch registers a PATCH handler under the given path.
func Patch(path string, handler HandlerType) {
Handle("PATCH", path, handler)
}
// Head registers a HEAD handler under the given path.
func Head(path string, handler HandlerType) {
Handle("HEAD", path, handler)
}
// Head registers a OPTIONS handler under the given path.
func Options(path string, handler HandlerType) {
Handle("OPTIONS", path, handler)
}
// Delete registers a DELETE handler under the given path.
func Delete(path string, handler HandlerType) {
Handle("DELETE", path, handler)
}
// NotFound registers a special handler for unregistered (404) paths.
// If handle is nil, use the default http.NotFound behavior.
func NotFound(handler HandlerType) {
// set up the default handler if needed
// we need to bless this so middleware will still run for a 404 request
if handler == nil {
handler = HandlerFunc(func(_ context.Context, w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
})
}
h := bless(wrap(handler))
routes.NotFoundHandler = func(w http.ResponseWriter, r *http.Request) {
h(w, r, nil)
}
}
// MethodNotAllowed registers a special handler for automatically responding
// to invalid method requests (405).
func MethodNotAllowed(handler HandlerType) {
if handler == nil {
handler = HandlerFunc(func(_ context.Context, w http.ResponseWriter, r *http.Request) {
http.Error(w,
http.StatusText(http.StatusMethodNotAllowed),
http.StatusMethodNotAllowed,
)
})
}
h := bless(wrap(handler))
routes.MethodNotAllowedHandler = func(w http.ResponseWriter, r *http.Request, methods map[string]httptreemux.HandlerFunc) {
if !enable405 {
routes.NotFoundHandler(w, r)
return
}
h(w, r, nil)
}
}
// EnableMethodNotAllowed enables or disables automatic Method Not Allowed handling.
// Note that this is enabled by default.
func EnableMethodNotAllowed(enabled bool) {
enable405 = enabled
}
// bless creates a new kamified handler using the global mux and middleware.
func bless(h ContextHandler) httptreemux.HandlerFunc {
k := kami{
handler: h,
base: &Context,
middleware: defaultMW,
panicHandler: &PanicHandler,
logHandler: &LogHandler,
}
return k.handle
}
// 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
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)
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)
}
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)
}
}
// Reset changes the root Context to context.Background().
// It removes every handler and all middleware.
func Reset() {
Context = context.Background()
PanicHandler = nil
LogHandler = nil
defaultMW = newWares()
routes = newRouter()
NotFound(nil)
MethodNotAllowed(nil)
}