This repository has been archived by the owner on Feb 24, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 579
/
app.go
82 lines (67 loc) · 2.04 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
80
81
82
package buffalo
import (
"fmt"
"net/http"
"sync"
"github.com/gobuffalo/envy"
"github.com/gorilla/mux"
)
// 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:"-"`
router *mux.Router
moot *sync.RWMutex
routes RouteList
root *App
children []*App
filepaths []string
// Routenamer for the app. This field provides the ability to override the
// base route namer for something more specific to the app.
RouteNamer RouteNamer
}
// 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 {
LoadPlugins()
envy.Load()
opts = optionsWithDefaults(opts)
a := &App{
Options: opts,
ErrorHandlers: ErrorHandlers{
http.StatusNotFound: defaultErrorHandler,
http.StatusInternalServerError: defaultErrorHandler,
},
router: mux.NewRouter(),
moot: &sync.RWMutex{},
routes: RouteList{},
children: []*App{},
RouteNamer: baseRouteNamer{},
}
dem := a.defaultErrorMiddleware
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 := fmt.Errorf(errorf, req.Method, req.URL.Path)
_ = a.ErrorHandlers.Get(code)(code, err, c)
}
}
a.router.NotFoundHandler = notFoundHandler("path not found: %s %s", http.StatusNotFound)
a.router.MethodNotAllowedHandler = notFoundHandler("method not found: %s %s", http.StatusMethodNotAllowed)
if a.MethodOverride == nil {
a.MethodOverride = MethodOverride
}
a.Use(a.PanicHandler)
a.Use(RequestLogger)
a.Use(sessionSaver)
return a
}