forked from gobuffalo/buffalo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
195 lines (172 loc) · 4.22 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
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
package buffalo
import (
"context"
"fmt"
"log"
"net/http"
"os"
"runtime"
"strings"
"sync"
"syscall"
"github.com/gorilla/mux"
"github.com/markbates/refresh/refresh/web"
"github.com/markbates/sigtx"
"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
ErrorHandlers ErrorHandlers
router *mux.Router
moot *sync.Mutex
routes RouteList
root *App
children []*App
}
// Start the application at the specified address/port and listen for OS
// interrupt and kill signals and will attempt to stop the application
// gracefully. This will also start the Worker process, unless WorkerOff is enabled.
func (a *App) Start(addr string) error {
if !strings.Contains(addr, ":") {
addr = fmt.Sprintf(":%s", addr)
}
fmt.Printf("Starting application at %s\n", addr)
server := http.Server{
Addr: addr,
Handler: a,
}
ctx, cancel := sigtx.WithCancel(a.Context, syscall.SIGTERM, os.Interrupt)
defer cancel()
go func() {
// gracefully shut down the application when the context is cancelled
<-ctx.Done()
fmt.Println("Shutting down application")
err := a.Stop(ctx.Err())
if err != nil {
fmt.Println(err)
}
if !a.WorkerOff {
// stop the workers
fmt.Println("Shutting down worker")
err = a.Worker.Stop()
if err != nil {
fmt.Println(err)
}
}
err = server.Shutdown(ctx)
if err != nil {
fmt.Println(err)
}
}()
// if configured to do so, start the workers
if !a.WorkerOff {
go func() {
err := a.Worker.Start(ctx)
if err != nil {
a.Stop(err)
}
}()
}
// start the web server
err := server.ListenAndServe()
if err != nil {
return a.Stop(err)
}
return nil
}
// Stop the application and attempt to gracefully shutdown
func (a *App) Stop(err error) error {
a.cancel()
if err != nil && errors.Cause(err) != context.Canceled {
fmt.Println(err)
return err
}
return nil
}
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ws := &Response{
ResponseWriter: w,
}
if a.MethodOverride != nil {
a.MethodOverride(w, r)
}
if ok := a.processPreHandlers(ws, r); !ok {
return
}
var h http.Handler
h = a.router
if a.Env == "development" {
h = web.ErrorChecker(h)
}
h.ServeHTTP(ws, r)
}
// New returns a new instance of App and adds some sane, and useful, defaults.
func New(opts Options) *App {
opts = optionsWithDefaults(opts)
a := &App{
Options: opts,
Middleware: newMiddlewareStack(),
ErrorHandlers: ErrorHandlers{
404: defaultErrorHandler,
500: defaultErrorHandler,
},
router: mux.NewRouter().StrictSlash(true),
moot: &sync.Mutex{},
routes: RouteList{},
children: []*App{},
}
a.router.NotFoundHandler = http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
c := a.newContext(RouteInfo{}, res, req)
err := errors.Errorf("path not found: %s", req.URL.Path)
a.ErrorHandlers.Get(404)(404, err, c)
})
if a.MethodOverride == nil {
a.MethodOverride = MethodOverride
}
a.Use(a.PanicHandler)
a.Use(RequestLogger)
a.Use(sessionSaver)
return a
}
// Automatic is deprecated, and will be removed in v0.10.0. Use buffalo.New instead.
func Automatic(opts Options) *App {
warningMsg := "Automatic is deprecated, and will be removed in v0.10.0. Use buffalo.New instead."
_, file, no, ok := runtime.Caller(1)
if ok {
warningMsg = fmt.Sprintf("%s Called from %s:%d", warningMsg, file, no)
}
log.Println(warningMsg)
return New(opts)
}
func (a *App) processPreHandlers(res http.ResponseWriter, req *http.Request) bool {
sh := func(h http.Handler) bool {
h.ServeHTTP(res, req)
if br, ok := res.(*Response); ok {
if (br.Status < 200 || br.Status > 299) && br.Status > 0 {
return false
}
if br.Size > 0 {
return false
}
}
return true
}
for _, ph := range a.PreHandlers {
if ok := sh(ph); !ok {
return false
}
}
last := http.Handler(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {}))
for _, ph := range a.PreWares {
last = ph(last)
if ok := sh(last); !ok {
return false
}
}
return true
}