forked from gobuffalo/buffalo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
79 lines (68 loc) · 1.93 KB
/
app.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
package buffalo
import (
"net/http"
"sync"
"github.com/gobuffalo/envy"
"github.com/gobuffalo/events"
"github.com/gorilla/mux"
"github.com/pkg/errors"
)
// App is where it all happens! It holds on to options,
// the underlying router, the middleware, and more.
// Without an App you can't do much!
type App struct {
Options
// Middleware returns the current MiddlewareStack for the App/Group.
Middleware *MiddlewareStack `json:"-"`
ErrorHandlers ErrorHandlers `json:"-"`
ErrorMiddleware MiddlewareFunc `json:"-"`
router *mux.Router
moot *sync.RWMutex
routes RouteList
root *App
children []*App
filepaths []string
}
// Muxer returns the underlying mux router to allow
// for advance configurations
func (a *App) Muxer() *mux.Router {
return a.router
}
// New returns a new instance of App and adds some sane, and useful, defaults.
func New(opts Options) *App {
events.LoadPlugins()
envy.Load()
opts = optionsWithDefaults(opts)
a := &App{
Options: opts,
ErrorHandlers: ErrorHandlers{
404: defaultErrorHandler,
500: defaultErrorHandler,
},
router: mux.NewRouter(),
moot: &sync.RWMutex{},
routes: RouteList{},
children: []*App{},
}
dem := a.defaultErrorMiddleware
if a.ErrorMiddleware != nil {
dem = a.ErrorMiddleware
}
a.Middleware = newMiddlewareStack(dem)
notFoundHandler := func(errorf string, code int) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
c := a.newContext(RouteInfo{}, res, req)
err := errors.Errorf(errorf, req.Method, req.URL.Path)
a.ErrorHandlers.Get(code)(code, err, c)
}
}
a.router.NotFoundHandler = notFoundHandler("path not found: %s %s", 404)
a.router.MethodNotAllowedHandler = notFoundHandler("method not found: %s %s", 405)
if a.MethodOverride == nil {
a.MethodOverride = MethodOverride
}
a.Use(a.PanicHandler)
a.Use(RequestLogger)
a.Use(sessionSaver)
return a
}