forked from aerogo/aero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Application.go
366 lines (300 loc) · 9.37 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
package aero
import (
"compress/gzip"
stdContext "context"
"errors"
"fmt"
"io"
"mime"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"sync"
"syscall"
"time"
"github.com/aerogo/csp"
"github.com/aerogo/session"
memstore "github.com/aerogo/session-store-memory"
"github.com/akyoto/color"
)
// Application represents a single web service.
type Application struct {
Config *Configuration
Sessions session.Manager
Security ApplicationSecurity
ContentSecurityPolicy *csp.ContentSecurityPolicy
router Router
rewrite []func(RewriteContext)
middleware []Middleware
pushConditions []func(Context) bool
contextPool sync.Pool
gzipWriterPool sync.Pool
pushOptions http.PushOptions
serversMutex sync.Mutex
servers [2]*http.Server
stop chan os.Signal
onStart []func()
onShutdown []func()
onPush []func(Context)
onError []func(Context, error)
}
// New creates a new application.
func New() *Application {
app := &Application{
Config: &Configuration{},
ContentSecurityPolicy: csp.New(),
stop: make(chan os.Signal, 1),
}
// Default CSP
app.ContentSecurityPolicy.SetMap(csp.Map{
"default-src": "'none'",
"img-src": "https:",
"media-src": "https:",
"script-src": "'self'",
"style-src": "'self'",
"font-src": "https:",
"manifest-src": "'self'",
"connect-src": "https: wss:",
"worker-src": "'self'",
"frame-src": "https:",
"base-uri": "'self'",
"form-action": "'self'",
})
// MIME types
_ = mime.AddExtensionType(".apng", "image/apng")
// Default SameSite value is "Lax"
app.Sessions.SameSite = http.SameSiteLaxMode
// Context pool
app.contextPool.New = func() interface{} {
return &context{
app: app,
}
}
// Push options describes the headers that are sent
// to our server to retrieve the push response.
app.pushOptions = http.PushOptions{
Method: "GET",
Header: http.Header{
acceptEncodingHeader: []string{"gzip"},
},
}
// Default session store: Memory
app.Sessions.Store = memstore.New()
// Configuration
app.Config.Reset()
app.Load()
return app
}
// Get registers your function to be called when the given GET path has been requested.
func (app *Application) Get(path string, handler Handler) {
app.router.Add(http.MethodGet, path, handler)
}
// Post registers your function to be called when the given POST path has been requested.
func (app *Application) Post(path string, handler Handler) {
app.router.Add(http.MethodPost, path, handler)
}
// Delete registers your function to be called when the given DELETE path has been requested.
func (app *Application) Delete(path string, handler Handler) {
app.router.Add(http.MethodDelete, path, handler)
}
// Put registers your function to be called when the given PUT path has been requested.
func (app *Application) Put(path string, handler Handler) {
app.router.Add(http.MethodPut, path, handler)
}
// Any registers your function to be called with any http method.
func (app *Application) Any(path string, handler Handler) {
app.Get(path, handler)
app.Post(path, handler)
app.Delete(path, handler)
app.Put(path, handler)
}
// Router returns the router used by the application.
func (app *Application) Router() *Router {
return &app.router
}
// Run starts your application.
func (app *Application) Run() {
signal.Notify(app.stop, os.Interrupt, syscall.SIGTERM)
app.BindMiddleware()
app.ListenAndServe()
for _, callback := range app.onStart {
callback()
}
<-app.stop
app.Shutdown()
}
// Use adds middleware to your middleware chain.
func (app *Application) Use(middlewares ...Middleware) {
app.middleware = append(app.middleware, middlewares...)
}
// Load loads the application configuration from config.json.
func (app *Application) Load() {
config, err := LoadConfig("config.json")
if err != nil {
// Ignore missing config file, we can perfectly run without one
return
}
app.Config = config
}
// ListenAndServe starts the server.
// It guarantees that a TCP listener is listening on the ports defined in the config
// when the function returns.
func (app *Application) ListenAndServe() {
if app.Security.Key != "" && app.Security.Certificate != "" {
listener := app.listen(":" + strconv.Itoa(app.Config.Ports.HTTPS))
go app.serveHTTPS(listener)
fmt.Println("Server running on:", color.GreenString("https://localhost:"+strconv.Itoa(app.Config.Ports.HTTPS)))
}
listener := app.listen(":" + strconv.Itoa(app.Config.Ports.HTTP))
go app.serveHTTP(listener)
fmt.Println("Server running on:", color.GreenString("http://localhost:"+strconv.Itoa(app.Config.Ports.HTTP)))
}
// Shutdown will gracefully shut down all servers.
func (app *Application) Shutdown() {
app.serversMutex.Lock()
defer app.serversMutex.Unlock()
for _, server := range app.servers {
shutdown(server, app.Config.Timeouts.Shutdown)
}
for _, callback := range app.onShutdown {
callback()
}
}
// OnStart registers a callback to be executed on server start.
func (app *Application) OnStart(callback func()) {
app.onStart = append(app.onStart, callback)
}
// OnEnd registers a callback to be executed on server shutdown.
func (app *Application) OnEnd(callback func()) {
app.onShutdown = append(app.onShutdown, callback)
}
// OnPush registers a callback to be executed when an HTTP/2 push happens.
func (app *Application) OnPush(callback func(Context)) {
app.onPush = append(app.onPush, callback)
}
// OnError registers a callback to be executed on server errors.
func (app *Application) OnError(callback func(Context, error)) {
app.onError = append(app.onError, callback)
}
// AddPushCondition registers a callback that
// needs to return true before an HTTP/2 push happens.
func (app *Application) AddPushCondition(test func(Context) bool) {
app.pushConditions = append(app.pushConditions, test)
}
// Rewrite adds a URL path rewrite function.
func (app *Application) Rewrite(rewrite func(RewriteContext)) {
app.rewrite = append(app.rewrite, rewrite)
}
// newContext returns a new context from the pool.
func (app *Application) newContext(req *http.Request, res http.ResponseWriter) *context {
ctx := app.contextPool.Get().(*context)
ctx.status = http.StatusOK
ctx.request.inner = req
ctx.response.inner = res
ctx.session = nil
ctx.paramCount = 0
ctx.modifierCount = 0
return ctx
}
// ServeHTTP responds to the given request.
func (app *Application) ServeHTTP(response http.ResponseWriter, request *http.Request) {
ctx := app.newContext(request, response)
for _, rewrite := range app.rewrite {
rewrite(ctx)
}
app.router.Lookup(request.Method, request.URL.Path, ctx)
if ctx.handler == nil {
response.WriteHeader(http.StatusNotFound)
ctx.Close()
return
}
err := ctx.handler(ctx)
if err != nil {
for _, callback := range app.onError {
callback(ctx, err)
}
}
ctx.Close()
}
// acquireGZipWriter will return a clean gzip writer from the pool.
func (app *Application) acquireGZipWriter(response io.Writer) *gzip.Writer {
var writer *gzip.Writer
obj := app.gzipWriterPool.Get()
if obj == nil {
writer, _ = gzip.NewWriterLevel(response, gzip.BestCompression)
return writer
}
writer = obj.(*gzip.Writer)
writer.Reset(response)
return writer
}
// BindMiddleware applies the middleware to every router node.
// This is called by `Run` automatically and should never be called
// outside of tests.
func (app *Application) BindMiddleware() {
app.router.bind(func(handler Handler) Handler {
return handler.Bind(app.middleware...)
})
}
// createServer creates an http server instance.
func (app *Application) createServer() *http.Server {
return &http.Server{
Handler: app,
ReadHeaderTimeout: app.Config.Timeouts.ReadHeader,
WriteTimeout: app.Config.Timeouts.Write,
IdleTimeout: app.Config.Timeouts.Idle,
TLSConfig: createTLSConfig(),
}
}
// listen returns a Listener for the given address.
func (app *Application) listen(address string) Listener {
listener, err := net.Listen("tcp", address)
if err != nil {
panic(err)
}
return Listener{listener.(*net.TCPListener)}
}
// serveHTTP serves requests from the given listener.
func (app *Application) serveHTTP(listener Listener) {
server := app.createServer()
app.serversMutex.Lock()
app.servers[0] = server
app.serversMutex.Unlock()
// This will block the calling goroutine until the server shuts down.
// The returned error is never nil and in case of a normal shutdown
// it will be `http.ErrServerClosed`.
err := server.Serve(listener)
if !errors.Is(err, http.ErrServerClosed) {
panic(err)
}
}
// serveHTTPS serves requests from the given listener.
func (app *Application) serveHTTPS(listener Listener) {
server := app.createServer()
app.serversMutex.Lock()
app.servers[1] = server
app.serversMutex.Unlock()
// This will block the calling goroutine until the server shuts down.
// The returned error is never nil and in case of a normal shutdown
// it will be `http.ErrServerClosed`.
err := server.ServeTLS(listener, app.Security.Certificate, app.Security.Key)
if !errors.Is(err, http.ErrServerClosed) {
panic(err)
}
}
// shutdown will gracefully shut down the server.
func shutdown(server *http.Server, timeout time.Duration) {
if server == nil {
return
}
// Add a timeout to the server shutdown
ctx, cancel := stdContext.WithTimeout(stdContext.Background(), timeout)
defer cancel()
// Shut down server
err := server.Shutdown(ctx)
if err != nil {
fmt.Println(err)
}
}