Middleware - noppoMan/Slimane GitHub Wiki
Middleware is functions that have access to the http request, the http response, and the next function in the application' s request-response cycle.
Types of the Middleware chain
case respond(Response)
: Respond to the content immediately with givenResponse
case next(Request, Response)
: Chain to the next middleware or the route.case error(Error)
: Abort the middleware chain and pass the error toapp.catch
Handler.
You can choose 2 types of middleware registration ways from handy or creating Middleware struct.
Register Middleware by Handy Style
app.use { request, response, responder in
do {
if let data = try File.synchronousRead("/path/to/file") {
response.data(data)
responder(.respond(response)) // respond to the read file content
} else {
responder(.next(request, response)) // Chaining to the next middleware or route
}
} catch {
responder(.error(error)) // Go to `catch` handler
}
}
Middleware Protocol
Confirmed Style
Register Middleware By struct FooMiddleware: Middleware {
func respond(_ request: Request, _ response: Response, _ responder: @escaping (Chainer) -> Void) {
do {
if let data = try File.synchronousRead("/path/to/file") {
response.data(data)
responder(.respond(response))
} else {
responder(.next(request, response))
}
} catch {
responder(.error(error))
}
}
}
app.use(FooMiddleware())