-
Notifications
You must be signed in to change notification settings - Fork 1
/
application.go
554 lines (458 loc) · 13 KB
/
application.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
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
package attache
import (
"bytes"
"errors"
"fmt"
"log"
"net/http"
"reflect"
"regexp"
"runtime"
"sort"
"strings"
"unicode"
"github.com/go-chi/chi/middleware"
"github.com/gorilla/securecookie"
)
// An Application routes HTTP traffic to an instance of its associated
// concrete Context type
type Application struct {
r router
providers stack
contextType reflect.Type
// NoLogging can be set to true to disable logging
NoLogging bool
logHandler http.Handler
}
// ServeHTTP implements http.Handler for *Application.
func (a *Application) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// call main handler func
if a.NoLogging {
a.baseHandler(w, r)
} else {
a.logHandler.ServeHTTP(w, r)
}
}
func (a *Application) baseHandler(w http.ResponseWriter, r *http.Request) {
// Ensure a's recovery method runs.
defer a.recover(w, r)
// Try to locate the handler stack for the request's path.
n := a.r.root.lookup(r.URL.Path)
if n == nil || (!n.hasMount() && len(n.methods) == 0) {
// No endpoint for the path; fail with a 404
Error(404)
}
// Create a local copy of n's stack.
var s stack
s = append(s, n.guard...)
// Short-circuit for mounted routes with no guards.
if n.hasMount() && len(s) == 0 {
n.mount.ServeHTTP(w, r)
return
}
if n.hasMount() {
// Add the mounted handler's ServeHTTP method to the stack
s = append(s, reflect.ValueOf(n.mount.ServeHTTP))
} else {
if mainStack := n.methods[strings.ToUpper(r.Method)]; mainStack != nil {
// Add the handlers from the main stack (optional BEFORE_..., [METHOD]_..., and optional AFTER_...)
// to the request handler stack
s = append(s, mainStack...)
} else {
// This particular HTTP method isn't allowed; fail with a 405
Error(405)
}
}
// Initialize an instance of the bootstrapped type.
ctx := reflect.New(a.contextType.Elem()).Interface().(Context)
// Initialize the context, or die with 500
if err := initContextInstance(ctx, w, r); err != nil {
log.Println(err)
httpResult{code: 500}.ServeHTTP(w, r)
return
}
// Create a new injector for this request.
// TODO: should we cache these?
injector := injector{
app: a,
ctx: ctx,
req: r,
res: w,
}
// Run all the registered providers and add their provided values to the injector.
for _, x := range a.providers {
result := x.Call(
[]reflect.Value{
reflect.ValueOf(ctx),
reflect.ValueOf(r),
},
)
injector.provided = append(injector.provided, reflect.ValueOf(result[0].Interface()))
}
// Execute the completed stack.
for _, x := range s {
injector.apply(x)
}
}
// Initialize a Context instance for use
func initContextInstance(ictx Context, w http.ResponseWriter, r *http.Request) error {
// set Request and ResponseWriter for this context
bctx := ictx.baseContext()
bctx.baseRw = w
bctx.baseReq = r
// Initialize views when context has view capability
if impl, ok := ictx.(HasViews); ok {
views, err := ViewCacheFor(impl.CONFIG_Views())
if err != nil {
return err
}
impl.SetViews(views)
}
// Initialize db when context has db capability
if impl, ok := ictx.(HasDB); ok {
db, err := DBFor(impl.CONFIG_DB())
if err != nil {
return err
}
impl.SetDB(db)
}
// Initialize session when context has session capability
if impl, ok := ictx.(HasSession); ok {
conf := impl.CONFIG_Session()
s, err := gsSessions.Get(r, conf.Name)
if err != nil {
log.Println(err)
}
s.Options.HttpOnly = true
impl.SetSession(Session{s})
}
// Initialize context
ictx.Init(w, r)
return nil
}
// recover is the deferred recovery handler run for each request
func (*Application) recover(w http.ResponseWriter, r *http.Request) {
val := recover()
if val == nil {
return
}
if impl, ok := val.(http.Handler); ok {
impl.ServeHTTP(w, r)
return
}
pc := make([]uintptr, 4)
pc = pc[:runtime.Callers(4, pc)]
buf := strings.Builder{}
for _, f := range pc {
fn := runtime.FuncForPC(f)
if fn != nil {
fmt.Fprint(&buf, "\ntrace: ", fn.Name())
}
}
log.Println("recovered: panic:", val, buf.String())
httpResult{code: 500}.ServeHTTP(w, r)
}
// Run starts listening for HTTP requests to the application at the given bind address,
// or the default of :8080 if none is specified.
func (a *Application) Run(addr ...string) error {
bindAddr := ":8080"
if len(addr) > 0 {
bindAddr = addr[0]
}
return http.ListenAndServe(bindAddr, a)
}
// RunWithServer binds the application to the server, and begins listening for HTTP requests.
func (a *Application) RunWithServer(s *http.Server) error {
s.Handler = a
return s.ListenAndServe()
}
// RunTLS starts listening for HTTPS requests to the application at the given bind address,
// or the default of :8443 if none is specified.
func (a *Application) RunTLS(certFile, keyFile string, addr ...string) error {
bindAddr := ":8443"
if len(addr) > 0 {
bindAddr = addr[0]
}
return http.ListenAndServeTLS(bindAddr, certFile, keyFile, a)
}
// RunWithServerTLS binds the application to the server, and begins listening for HTTPS requests.
func (a *Application) RunWithServerTLS(s *http.Server, certFile, keyFile string) error {
s.Handler = a
return s.ListenAndServeTLS(certFile, keyFile)
}
var (
methodRx = regexp.MustCompile(`^(GET|PUT|POST|PATCH|DELETE|HEAD|OPTIONS|TRACE|ALL)_(.*)$`)
)
// Bootstrap attempts to create an Application to serve requests for
// the provided concrete Context type. If an error is encountered
// during the bootstrapping process, it is returned.
// If a nil *Application is returned, the returned error will be non-nil.
func Bootstrap(ctxType Context) (*Application, error) {
var (
v = reflect.ValueOf(ctxType)
t = v.Type()
a = Application{
r: newrouter(),
}
)
if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct {
return nil, fmt.Errorf("expecting pointer to a struct, got %T", ctxType)
}
a.contextType = t
if err := bootstrapContextInit(ctxType); err != nil {
return nil, err
}
if err := bootstrapRouter(&a, ctxType); err != nil {
return nil, err
}
// set up logHandler
a.logHandler = middleware.DefaultLogger(http.HandlerFunc(a.baseHandler))
return &a, nil
}
func bootstrapContextInit(impl Context) error {
// Attempt to load environment first, if supported by context
if impl, ok := impl.(HasEnvironment); ok {
conf := impl.CONFIG_Environment()
if err := LoadEnvironment(conf); err != nil {
return BootstrapError{Cause: err, Phase: "load environment"}
}
}
// Attempt to load views, if supported by context
if impl, ok := impl.(HasViews); ok {
_, err := ViewCacheFor(impl.CONFIG_Views())
if err != nil {
return BootstrapError{Cause: err, Phase: "init views"}
}
}
// Attempt db connection, if supported by context
if impl, ok := impl.(HasDB); ok {
_, err := DBFor(impl.CONFIG_DB())
if err != nil {
return BootstrapError{Cause: err, Phase: "init database"}
}
}
// Examine session config for validity
if impl, ok := impl.(HasSession); ok {
conf := impl.CONFIG_Session()
if len(conf.Secret) == 0 {
return BootstrapError{Cause: errors.New("empty secret"), Phase: "check session config"}
}
gsSessions.Codecs = append(gsSessions.Codecs, securecookie.CodecsFromPairs(conf.Secret)...)
}
return nil
}
func bootstrapRouter(a *Application, impl Context) error {
v := reflect.ValueOf(impl)
t := v.Type()
// Types only used for bootstrapping.
// Defined in scope to unclutter the global namespace.
type (
// A guard represents a guard definition
guard struct {
path string
stack stack
}
// A route represents an endpoint definition
route struct {
method string
path string
stack stack
}
// A mount represents a mount definition
mount struct {
path string
handler http.Handler
}
)
// Pre-allocate slices for guard, route, and mount definitions
guards := make([]guard, 0, 32)
routes := make([]route, 0, 32)
mounts := make([]mount, 0, 32)
// The function signature expected of MOUNT_ methods, as a reflect.Type
mountFnTyp := reflect.TypeOf((func() (http.Handler, error))(nil))
// The function signature expected of PROVIDE_ methods, as a reflect.Type
provideFnTyp := reflect.TypeOf((func(*http.Request) interface{})(nil))
for i := 0; i < t.NumMethod(); i++ {
m := t.Method(i)
// Provider methods
if strings.HasPrefix(m.Name, "PROVIDE_") {
fnTyp := v.Method(m.Index).Type()
if !fnTyp.ConvertibleTo(provideFnTyp) {
return BootstrapError{
Cause: fmt.Errorf("%s does not have signature %s", m.Name, provideFnTyp),
Phase: fmt.Sprint("check provider ", m.Name),
}
}
a.providers = append(a.providers, m.Func)
}
// Route methods
if match := methodRx.FindStringSubmatch(m.Name); match != nil {
meth, path := match[1], pathForName(match[2])
rt := route{
method: meth,
path: path,
stack: make(stack, 0, 3),
}
if bm, ok := t.MethodByName("BEFORE_" + match[2]); ok {
rt.stack = append(rt.stack, bm.Func)
}
rt.stack = append(rt.stack, m.Func)
if am, ok := t.MethodByName("AFTER_" + match[2]); ok {
rt.stack = append(rt.stack, am.Func)
}
routes = append(routes, rt)
continue
}
// Guard methods
if strings.HasPrefix(m.Name, "GUARD_") {
path := pathForName(m.Name[6:] /* strip GUARD_ prefix */)
guards = append(guards, guard{
path: path,
stack: stack{m.Func},
})
continue
}
// Mount methods
if strings.HasPrefix(m.Name, "MOUNT_") {
path := pathForName(m.Name[6:])
mt := mount{
path: path,
}
fnVal := v.Method(m.Index)
fnValTyp := fnVal.Type()
if !fnValTyp.ConvertibleTo(mountFnTyp) {
return BootstrapError{
Cause: fmt.Errorf("%s does not have signature %s", m.Name, mountFnTyp),
Phase: fmt.Sprintf("mount %s", path),
}
}
h, err := fnVal.
Convert(mountFnTyp).
Interface().(func() (http.Handler, error))()
if err != nil {
return BootstrapError{
Cause: fmt.Errorf("error: %s", err),
Phase: fmt.Sprintf("mount %s", path),
}
}
mt.handler = h
mounts = append(mounts, mt)
continue
}
}
// Bootstrap was called for a type that didn't provide any final request handlers (routes or mounts)ß.
// This is most likely developer error.
// Rather than silently continue, we'll warn the developer and fail.
if len(routes)+len(mounts) == 0 {
return BootstrapError{
Phase: "register routes",
Cause: errors.New("no routes defined"),
}
}
// The order of insertion is important for guards, mounts, and routes.
// In order to ensure correctness, we need to sort all 3 lists with
// the same set of rules: by path length (short to long), then alphabetically.
sort.SliceStable(guards, func(i, j int) bool {
var (
pathI, pathJ = guards[i].path, guards[j].path
lenI, lenJ = len(pathI), len(pathJ)
)
if lenI == lenJ {
return pathI < pathJ
}
return lenI < lenJ
})
sort.SliceStable(mounts, func(i, j int) bool {
var (
pathI, pathJ = mounts[i].path, mounts[j].path
lenI, lenJ = len(pathI), len(pathJ)
)
if lenI == lenJ {
return pathI < pathJ
}
return lenI < lenJ
})
sort.SliceStable(routes, func(i, j int) bool {
var (
pathI, pathJ = routes[i].path, routes[j].path
lenI, lenJ = len(pathI), len(pathJ)
)
if lenI == lenJ {
return pathI < pathJ
}
return lenI < lenJ
})
// Once we've sorted the guards, mounts, and routes, we can
// actually register them to the Application's router
for _, g := range guards {
if err := a.r.guard(g.path, g.stack); err != nil {
return BootstrapError{
Phase: fmt.Sprintf("guard %s", g.path),
Cause: err,
}
}
}
for _, mt := range mounts {
if err := a.r.mount(mt.path, mt.handler); err != nil {
return BootstrapError{
Phase: fmt.Sprintf("mount %s", mt.path),
Cause: err,
}
}
}
for _, rt := range routes {
if rt.method == "ALL" {
if err := a.r.all(rt.path, rt.stack); err != nil {
return BootstrapError{
Phase: fmt.Sprintf("route %s %s", rt.method, rt.path),
Cause: err,
}
}
} else {
if err := a.r.handle(rt.method, rt.path, rt.stack); err != nil {
return BootstrapError{
Phase: fmt.Sprintf("route %s %s", rt.method, rt.path),
Cause: err,
}
}
}
}
// Development: log the list of registered routes, etc.
var b bytes.Buffer
b.WriteString("\n======= ROUTES =======\n")
dump(a.r.root, "", 0, &b)
b.WriteString("======================")
log.Println(b.String())
return nil
}
// Calculates an HTTP request path based on a go method name.
func pathForName(name string) string {
// Ignore (i.e remove) any underscores
name = strings.Replace(name, "_", "", -1)
result := strings.Builder{}
size := len(name)
start := 0
lastUpper := false
for i := 0; i < size; i++ {
r := rune(name[i])
if unicode.IsUpper(r) {
if !lastUpper && i != start {
result.WriteByte('/')
result.WriteString(strings.ToLower(name[start:i]))
start = i
}
lastUpper = true
} else {
if lastUpper && i-1 != start {
result.WriteByte('/')
result.WriteString(strings.ToLower(name[start : i-1]))
start = i - 1
}
lastUpper = false
}
}
// Make sure we encode the last segment
result.WriteByte('/')
result.WriteString(strings.ToLower(name[start:]))
return result.String()
}