File not found middleware for the Website service (#4)
This PR contains the work done to add a `NotFoundMiddleware` middleware to the Website service so requests matching neither a route nor a static file return a custom 404.html page with a 404 Not Found status. Also enables index.html fallback so the landing page is served at the site root. To provider further details about the work done: * NotFoundMiddleware — intercepts the `.notFound` error from the `FileMiddleware` middleware and serves the preloaded error page with the correct content type; all other errors propagate. Falls back to a minimal body if the file is missing. * Router — wires the `NotFoundMiddleware` middleware ahead of the `FileMiddleware` and enables searchForIndexHtml. * Package — adds the **Hummingbird** product to the Library target. * Tooling — sets a custom working directory in the Xcode scheme; removes the unused `pkg-deps` target from the `Makefile` file. Reviewed-on: rock-n-code/loud-amsterdam#4 Co-authored-by: Javier Cicchelli <javier@rock-n-code.com> Co-committed-by: Javier Cicchelli <javier@rock-n-code.com>
This commit is contained in:
@@ -65,8 +65,9 @@ private func logger(
|
||||
|
||||
/// Builds the application's router.
|
||||
///
|
||||
/// Registers the request-logging middleware and the static file middleware that serves
|
||||
/// the contents of `staticFilesPath`.
|
||||
/// Registers, in order, the request-logging middleware, the not-found middleware that serves
|
||||
/// the error page, and the static file middleware that serves the contents of `staticFilesPath`
|
||||
/// (falling back to `index.html` for directory requests).
|
||||
/// - Parameters:
|
||||
/// - staticFilesPath: the folder, relative to the working directory, the static files are served from.
|
||||
/// - logLevel: the level the request-logging middleware logs at.
|
||||
@@ -79,9 +80,10 @@ private func router(
|
||||
|
||||
router.addMiddleware {
|
||||
LogRequestsMiddleware(logLevel)
|
||||
NotFoundMiddleware(staticFilesPath)
|
||||
FileMiddleware(
|
||||
staticFilesPath,
|
||||
searchForIndexHtml: false
|
||||
searchForIndexHtml: true
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import Foundation
|
||||
import Hummingbird
|
||||
import NIOCore
|
||||
|
||||
/// Serves a custom error page for requests that match neither a route nor a static file.
|
||||
///
|
||||
/// Placed ahead of `FileMiddleware` in the middleware chain, it catches the `.notFound` error
|
||||
/// that bubbles up when no file exists for the requested path and responds with the preloaded
|
||||
/// error page and a `404 Not Found` status.
|
||||
public struct NotFoundMiddleware<Context: RequestContext> {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The body of the error page served on a not-found response.
|
||||
private let page: ByteBuffer
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a middleware that serves the error page (`404.html`) from the static files folder.
|
||||
///
|
||||
/// The page is read once, at construction. A minimal fallback body is used when the file is
|
||||
/// missing.
|
||||
/// - Parameter staticFilesPath: the folder, relative to the working directory, the static files are served from.
|
||||
public init(
|
||||
_ staticFilesPath: String
|
||||
) {
|
||||
let path = StaticFile.errorHTML.path(relativeTo: staticFilesPath)
|
||||
|
||||
if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
|
||||
self.init(page: .init(bytes: data))
|
||||
} else {
|
||||
self.init(page: .init(string: "404 Not Found"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a middleware that serves the given error page on a not-found response.
|
||||
/// - Parameter page: the body of the error page.
|
||||
init(
|
||||
page: ByteBuffer
|
||||
) {
|
||||
self.page = page
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - RouterMiddleware
|
||||
|
||||
extension NotFoundMiddleware: RouterMiddleware {
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
public func handle(
|
||||
_ request: Request,
|
||||
context: Context,
|
||||
next: (Request, Context) async throws -> Response
|
||||
) async throws -> Response {
|
||||
do {
|
||||
return try await next(request, context)
|
||||
} catch let error {
|
||||
// Only intercept "not found"; let every other error propagate.
|
||||
guard
|
||||
let responseError = error as? any HTTPResponseError,
|
||||
responseError.status == .notFound
|
||||
else {
|
||||
throw error
|
||||
}
|
||||
|
||||
var headers = HTTPFields()
|
||||
|
||||
headers[.contentType] = StaticFile.errorHTML.contentType
|
||||
|
||||
return Response(
|
||||
status: .notFound,
|
||||
headers: headers,
|
||||
body: .init(byteBuffer: page)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user