This repository has been archived by the owner on Aug 19, 2022. It is now read-only.
forked from guregu/kami
/
kami.go
191 lines (160 loc) · 5.46 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
package kami
import (
"net/http"
"github.com/julienschmidt/httprouter"
"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)
// CloseHandler will, if set, called before the log handler and can be used for cleanup actions
CloseHandler func(context.Context, *http.Request)
)
var routes = httprouter.New()
func init() {
// set up the default 404/405 handlers
NotFound(nil)
MethodNotAllowed(nil)
}
// 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, defaultBless(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 := defaultBless(wrap(handler))
routes.NotFound = http.HandlerFunc(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 := defaultBless(wrap(handler))
routes.MethodNotAllowed = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h(w, r, nil)
})
}
// EnableMethodNotAllowed enables or disables automatic Method Not Allowed handling.
// Note that this is enabled by default.
func EnableMethodNotAllowed(enabled bool) {
routes.HandleMethodNotAllowed = enabled
}
func defaultBless(k ContextHandler) httprouter.Handle {
return bless(k, &Context, defaultMW, &PanicHandler, &LogHandler, &CloseHandler)
}
// bless is the meat of kami.
// It wraps a ContextHandler into an httprouter compatible request,
// in order to run all the middleware and other special handlers.
func bless(k ContextHandler, base *context.Context, m *middlewares, panicHandler *HandlerType, logHandler *func(context.Context, mutil.WriterProxy, *http.Request), closeHandler *func(context.Context, *http.Request)) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
ctx := defaultContext(*base, r)
if len(params) > 0 {
ctx = newContextWithParams(ctx, params)
}
ranLogHandler := false // track this in case the log handler blows up
ranCloseHandler := false // track this in case the log handler blows up
writer := w
var proxy mutil.WriterProxy
if *logHandler != nil {
proxy = mutil.WrapWriter(w)
writer = proxy
}
if *panicHandler != nil {
defer func() {
if err := recover(); err != nil {
ctx = newContextWithException(ctx, err)
wrap(*panicHandler).ServeHTTPContext(ctx, writer, r)
if *closeHandler != nil && !ranCloseHandler {
(*closeHandler)(ctx, r)
}
if *logHandler != nil && !ranLogHandler {
(*logHandler)(ctx, proxy, r)
// should only happen if header hasn't been written
proxy.WriteHeader(http.StatusInternalServerError)
}
}
}()
}
ctx, ok := m.run(ctx, writer, r)
if ok {
k.ServeHTTPContext(ctx, writer, r)
}
if *closeHandler != nil {
ranCloseHandler = true
(*closeHandler)(ctx, 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
CloseHandler = nil
defaultMW = newMiddlewares()
routes = httprouter.New()
NotFound(nil)
MethodNotAllowed(nil)
}