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
84 lines (70 loc) · 2.09 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
83
84
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, ErrorHandlers, router, and filepaths are moved to Home.
Home
moot *sync.RWMutex
routes RouteList
// TODO: to be deprecated #road-to-v1
root *App
children []*App
// 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,
Home: Home{
name: opts.Name,
host: opts.Host,
prefix: opts.Prefix,
ErrorHandlers: ErrorHandlers{
http.StatusNotFound: defaultErrorHandler,
http.StatusInternalServerError: defaultErrorHandler,
},
router: mux.NewRouter(),
},
moot: &sync.RWMutex{},
routes: RouteList{},
children: []*App{},
RouteNamer: baseRouteNamer{},
}
a.Home.app = a // replace root.
a.Home.appSelf = a // temporary, reverse reference to the group app.
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.Middleware = newMiddlewareStack(RequestLogger)
a.Use(a.defaultErrorMiddleware)
a.Use(a.PanicHandler)
return a
}