-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhandler.go
More file actions
251 lines (214 loc) · 6.4 KB
/
handler.go
File metadata and controls
251 lines (214 loc) · 6.4 KB
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
// Copyright (C) 2012 Numerotron Inc.
// Use of this source code is governed by an MIT-style license
// that can be found in the LICENSE file.
package bingo
import (
"compress/gzip"
"errors"
"fmt"
"io"
"net/http"
"reflect"
"runtime/debug"
"strings"
"time"
)
type ContextBuilder func(*http.Request, http.ResponseWriter, *Session) Context
type ContextHandlerFunc func(Context) *AppError
var NotifyRequestTime func(elapsed time.Duration, path string)
func newHandler(fn func(http.ResponseWriter, *http.Request, *Session)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
session := loadSession(r)
fn(w, r, session)
elapsed := time.Since(start)
fmt.Printf("%s - request time: %.3f ms", r.URL.Path, float64(elapsed)/float64(time.Millisecond))
if NotifyRequestTime != nil {
NotifyRequestTime(elapsed, r.URL.Path)
}
}
}
func newContext(fn ContextHandlerFunc, builder ContextBuilder) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
session := loadSession(r)
context := builder(r, w, session)
defer func(c Context) {
if err := recover(); err != nil {
serr := fmt.Sprintf("runtime error: %s", err)
apperr := new(AppError)
apperr.Message = serr
apperr.Code = 500
apperr.Err = errors.New(serr)
handleError(c, apperr)
}
}(context)
proceed, err := context.Before()
if err != nil {
handleError(context, ServerError(err, "before error occurred"))
return
}
if !proceed {
return
}
if e := fn(context); e != nil {
if e.Err != http.ErrBodyNotAllowed {
fmt.Printf("error: %s (%T)\n", e.Err, e.Err)
switch e.Code {
case 404:
renderNotFound(context)
default:
handleError(context, e)
}
}
}
context.After()
elapsed := time.Since(start)
LogAccess(context.Request(), elapsed)
if NotifyRequestTime != nil {
NotifyRequestTime(elapsed, r.URL.Path)
}
}
}
func newReflect(pattern string, handler interface{}, builder ContextBuilder) http.HandlerFunc {
methods := make(map[string]reflect.Method)
t := reflect.TypeOf(handler)
for i := 0; i < t.NumMethod(); i++ {
m := t.Method(i)
methods[strings.ToLower(m.Name)] = m
}
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
session := loadSession(r)
context := builder(r, w, session)
defer func(c Context) {
if err := recover(); err != nil {
serr := fmt.Sprintf("runtime error: %s", err)
apperr := new(AppError)
apperr.Message = serr
apperr.Code = 500
apperr.Err = errors.New(serr)
handleError(c, apperr)
}
}(context)
context.Before()
pieces := Path(r, len(pattern))
var result []reflect.Value
switch len(pieces) {
case 0:
m, ok := methods["index"]
if !ok {
renderNotFound(context)
return
}
result = m.Func.Call([]reflect.Value{reflect.ValueOf(handler), reflect.ValueOf(context)})
default:
m, ok := methods[pieces[0]]
if !ok {
renderNotFound(context)
return
}
switch m.Type.NumIn() {
case 3:
result = m.Func.Call([]reflect.Value{reflect.ValueOf(handler), reflect.ValueOf(context), reflect.ValueOf(pieces[1:])})
case 2:
result = m.Func.Call([]reflect.Value{reflect.ValueOf(handler), reflect.ValueOf(context)})
default:
renderNotFound(context)
return
}
}
if len(result) != 1 {
panic("result should be len(1)")
}
e := result[0].Interface().(*AppError)
if e != nil {
switch e.Code {
case 404:
renderNotFound(context)
default:
handleError(context, e)
}
return
}
context.After()
elapsed := time.Since(start)
fmt.Printf("%s - request time: %.3f ms\n", r.URL.Path, float64(elapsed)/float64(time.Millisecond))
if NotifyRequestTime != nil {
NotifyRequestTime(elapsed, r.URL.Path)
}
}
}
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (w gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func makeGzipHandler(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
fn(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
// XXX without this, it sniffs the content type based on the actual
// XXX content and uses application/gzip. If content isn't html,
// XXX set header yourself. RenderJSON does it, for example.
w.Header().Set("Content-Type", "text/html; charset=utf-8")
gz := gzip.NewWriter(w)
defer gz.Close()
fn(gzipResponseWriter{Writer: gz, ResponseWriter: w}, r)
}
}
func handle(pattern string, fn http.HandlerFunc) {
// handle everything below this pattern
http.HandleFunc(pattern+"/", fn)
// this has to come second to override http pkg default, which will add a
// permanent redirect for the non-slash pattern to the slash pattern
http.HandleFunc(pattern, fn)
}
func HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request, *Session)) {
handle(pattern, newHandler(handler))
}
func HandleContext(pattern string, handler ContextHandlerFunc, builder ContextBuilder) {
handle(pattern, newContext(handler, builder))
}
func HandleContextGzip(pattern string, handler ContextHandlerFunc, builder ContextBuilder) {
handle(pattern, makeGzipHandler(newContext(handler, builder)))
}
func HandleReflect(pattern string, handler interface{}, builder ContextBuilder) {
handle(pattern, newReflect(pattern, handler, builder))
}
// pass in something like "images" to serve /images
func HandleFiles(path string) {
pattern := fmt.Sprintf("/%s/", path)
prefix := fmt.Sprintf("/%s", path)
local := fmt.Sprintf("%s/%s", ContentDir, path)
http.Handle(pattern, http.StripPrefix(prefix, http.FileServer(http.Dir(local))))
}
func handleError(c Context, aerr *AppError) {
if Environment == EnvDevel {
handleErrorInDev(c, aerr)
return
}
renderError(c, aerr.Message)
if AfterErrorFunc != nil {
AfterErrorFunc(c, aerr)
}
}
func handleErrorInDev(c Context, aerr *AppError) {
fmt.Fprintln(c.Writer(), "An error occurred handling:", c.Request().URL.Path)
fmt.Fprintln(c.Writer(), "")
fmt.Fprintln(c.Writer(), aerr.Message)
fmt.Fprintln(c.Writer(), aerr.Err)
fmt.Fprintln(c.Writer(), "")
fmt.Fprintln(c.Writer(), "Stack trace:")
fmt.Fprintln(c.Writer(), string(debug.Stack()))
fmt.Println("An error occurred handling:", c.Request().URL.Path)
fmt.Println(aerr.Message)
fmt.Println(aerr.Err)
fmt.Println("Stack trace:")
fmt.Println(string(debug.Stack()))
}