HTML rendering support for the Website service (#5)
This PR contains the work done to replace the use of static _HTML_ files with type-safe HTML rendered server-side via **Elementary** through **Hummingbird**. To provide further details about the work done: * Added the **Elementary** dependencies. * Added the `IndexPage` and `ErrorPage` pages, ported from the old HTML boilerplate; removed the static files. * Added the `RootController` controller serving GET / using the `IndexPage` page, wired into the router. * Reworked the `NotFoundMiddleware` middleare to render `ErrorPage` page directly; non-notFound errors still propagate. * the `FileMiddleware` middleware no longer searches for any static `index.html` file. * Simplified the `StaticFile` enumeration, dropped unused constants and now-unnecessary throws. Reviewed-on: rock-n-code/loud-amsterdam#5 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:
@@ -19,6 +19,14 @@ let package = Package(
|
|||||||
)
|
)
|
||||||
],
|
],
|
||||||
dependencies: [
|
dependencies: [
|
||||||
|
.package(
|
||||||
|
url: "https://github.com/elementary-swift/elementary.git",
|
||||||
|
from: "0.6.0"
|
||||||
|
),
|
||||||
|
.package(
|
||||||
|
url: "https://github.com/hummingbird-community/hummingbird-elementary.git",
|
||||||
|
from: "0.3.0"
|
||||||
|
),
|
||||||
.package(
|
.package(
|
||||||
url: "https://github.com/hummingbird-project/hummingbird.git",
|
url: "https://github.com/hummingbird-project/hummingbird.git",
|
||||||
from: "2.25.0"
|
from: "2.25.0"
|
||||||
@@ -55,10 +63,18 @@ let package = Package(
|
|||||||
name: "Configuration",
|
name: "Configuration",
|
||||||
package: "swift-configuration"
|
package: "swift-configuration"
|
||||||
),
|
),
|
||||||
|
.product(
|
||||||
|
name: "Elementary",
|
||||||
|
package: "elementary"
|
||||||
|
),
|
||||||
.product(
|
.product(
|
||||||
name: "Hummingbird",
|
name: "Hummingbird",
|
||||||
package: "hummingbird"
|
package: "hummingbird"
|
||||||
),
|
),
|
||||||
|
.product(
|
||||||
|
name: "HummingbirdElementary",
|
||||||
|
package: "hummingbird-elementary"
|
||||||
|
),
|
||||||
],
|
],
|
||||||
path: "Sources/Library"
|
path: "Sources/Library"
|
||||||
),
|
),
|
||||||
@@ -77,6 +93,18 @@ let package = Package(
|
|||||||
name: "WebsiteCoreTests",
|
name: "WebsiteCoreTests",
|
||||||
dependencies: [
|
dependencies: [
|
||||||
.byName(name: "WebsiteCore"),
|
.byName(name: "WebsiteCore"),
|
||||||
|
.product(
|
||||||
|
name: "Elementary",
|
||||||
|
package: "elementary"
|
||||||
|
),
|
||||||
|
.product(
|
||||||
|
name: "Hummingbird",
|
||||||
|
package: "hummingbird"
|
||||||
|
),
|
||||||
|
.product(
|
||||||
|
name: "HummingbirdTesting",
|
||||||
|
package: "hummingbird"
|
||||||
|
),
|
||||||
],
|
],
|
||||||
path: "Tests/Library"
|
path: "Tests/Library"
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -1,62 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html lang="en">
|
|
||||||
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8">
|
|
||||||
<title>Page Not Found</title>
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
||||||
<style>
|
|
||||||
* {
|
|
||||||
line-height: 1.2;
|
|
||||||
margin: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
html {
|
|
||||||
color: #888;
|
|
||||||
display: table;
|
|
||||||
font-family: sans-serif;
|
|
||||||
height: 100%;
|
|
||||||
text-align: center;
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
body {
|
|
||||||
display: table-cell;
|
|
||||||
vertical-align: middle;
|
|
||||||
margin: 2em auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
h1 {
|
|
||||||
color: #555;
|
|
||||||
font-size: 2em;
|
|
||||||
font-weight: 400;
|
|
||||||
}
|
|
||||||
|
|
||||||
p {
|
|
||||||
margin: 0 auto;
|
|
||||||
width: 280px;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media only screen and (max-width: 280px) {
|
|
||||||
|
|
||||||
body,
|
|
||||||
p {
|
|
||||||
width: 95%;
|
|
||||||
}
|
|
||||||
|
|
||||||
h1 {
|
|
||||||
font-size: 1.5em;
|
|
||||||
margin: 0 0 0.3em;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body>
|
|
||||||
<h1>Page Not Found</h1>
|
|
||||||
<p>Sorry, but the page you were trying to view does not exist.</p>
|
|
||||||
</body>
|
|
||||||
|
|
||||||
</html>
|
|
||||||
<!-- IE needs 512+ bytes: https://docs.microsoft.com/archive/blogs/ieinternals/friendly-http-error-pages -->
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html lang="">
|
|
||||||
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
||||||
<title></title>
|
|
||||||
<link rel="stylesheet" href="css/style.css">
|
|
||||||
<meta name="description" content="">
|
|
||||||
|
|
||||||
<meta property="og:title" content="">
|
|
||||||
<meta property="og:type" content="">
|
|
||||||
<meta property="og:url" content="">
|
|
||||||
<meta property="og:image" content="">
|
|
||||||
<meta property="og:image:alt" content="">
|
|
||||||
|
|
||||||
<link rel="icon" href="/favicon.ico" sizes="any">
|
|
||||||
<link rel="icon" href="/icon.svg" type="image/svg+xml">
|
|
||||||
<link rel="apple-touch-icon" href="icon.png">
|
|
||||||
|
|
||||||
<link rel="manifest" href="site.webmanifest">
|
|
||||||
<meta name="theme-color" content="#fafafa">
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body>
|
|
||||||
|
|
||||||
<!-- Add your site or application content here -->
|
|
||||||
<p>Hello world! This is HTML5 Boilerplate.</p>
|
|
||||||
<script src="js/app.js"></script>
|
|
||||||
|
|
||||||
</body>
|
|
||||||
|
|
||||||
</html>
|
|
||||||
@@ -9,10 +9,9 @@ import WebsiteCore
|
|||||||
/// then assembles the router, server configuration, and logger.
|
/// then assembles the router, server configuration, and logger.
|
||||||
/// - Parameter reader: the configuration reader the values are read from.
|
/// - Parameter reader: the configuration reader the values are read from.
|
||||||
/// - Returns: the configured application, ready to run as a service.
|
/// - Returns: the configured application, ready to run as a service.
|
||||||
/// - Throws: an error if the router fails to build.
|
|
||||||
func application(
|
func application(
|
||||||
reader: ConfigReader
|
reader: ConfigReader
|
||||||
) async throws -> some ApplicationProtocol {
|
) async -> some ApplicationProtocol {
|
||||||
let logLevel = reader.string(
|
let logLevel = reader.string(
|
||||||
forKey: .Log.level,
|
forKey: .Log.level,
|
||||||
as: Logger.Level.self,
|
as: Logger.Level.self,
|
||||||
@@ -65,9 +64,9 @@ private func logger(
|
|||||||
|
|
||||||
/// Builds the application's router.
|
/// Builds the application's router.
|
||||||
///
|
///
|
||||||
/// Registers, in order, the request-logging middleware, the not-found middleware that serves
|
/// Registers the request-logging middleware, the not-found middleware that serves the error
|
||||||
/// the error page, and the static file middleware that serves the contents of `staticFilesPath`
|
/// page, and the static file middleware that serves the contents of `staticFilesPath`, then
|
||||||
/// (falling back to `index.html` for directory requests).
|
/// adds the `RootController` routes that render the landing page.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - staticFilesPath: the folder, relative to the working directory, the static files are served from.
|
/// - staticFilesPath: the folder, relative to the working directory, the static files are served from.
|
||||||
/// - logLevel: the level the request-logging middleware logs at.
|
/// - logLevel: the level the request-logging middleware logs at.
|
||||||
@@ -80,12 +79,11 @@ private func router(
|
|||||||
|
|
||||||
router.addMiddleware {
|
router.addMiddleware {
|
||||||
LogRequestsMiddleware(logLevel)
|
LogRequestsMiddleware(logLevel)
|
||||||
NotFoundMiddleware(staticFilesPath)
|
NotFoundMiddleware()
|
||||||
FileMiddleware(
|
FileMiddleware(staticFilesPath)
|
||||||
staticFilesPath,
|
|
||||||
searchForIndexHtml: true
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
router.addRoutes(RootController<AppRequestContext>().routes)
|
||||||
|
|
||||||
return router
|
return router
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ struct App {
|
|||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
let app = try await application(
|
let app = await application(
|
||||||
reader: reader
|
reader: reader
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
import Foundation
|
|
||||||
|
|
||||||
/// A static file shipped with the website service.
|
/// A static file shipped with the website service.
|
||||||
///
|
///
|
||||||
/// Each case identifies a file stored under the static files root (the `Resources/Static`
|
/// Each case identifies a file stored under the static files root (the `Resources/Static`
|
||||||
@@ -7,16 +5,12 @@ import Foundation
|
|||||||
enum StaticFile: CaseIterable, Sendable {
|
enum StaticFile: CaseIterable, Sendable {
|
||||||
/// The `js/app.js` script.
|
/// The `js/app.js` script.
|
||||||
case appJS
|
case appJS
|
||||||
/// The `404.html` error page.
|
|
||||||
case errorHTML
|
|
||||||
/// The `favicon.ico` icon.
|
/// The `favicon.ico` icon.
|
||||||
case faviconICO
|
case faviconICO
|
||||||
/// The `icon.png` icon.
|
/// The `icon.png` icon.
|
||||||
case iconPNG
|
case iconPNG
|
||||||
/// The `icon.svg` icon.
|
/// The `icon.svg` icon.
|
||||||
case iconSVG
|
case iconSVG
|
||||||
/// The `index.html` landing page.
|
|
||||||
case indexHTML
|
|
||||||
/// The `robots.txt` crawler directives.
|
/// The `robots.txt` crawler directives.
|
||||||
case robotsTXT
|
case robotsTXT
|
||||||
/// The `site.webmanifest` web application manifest.
|
/// The `site.webmanifest` web application manifest.
|
||||||
@@ -32,8 +26,6 @@ extension StaticFile {
|
|||||||
enum Extension: String, Sendable {
|
enum Extension: String, Sendable {
|
||||||
/// A Cascading Style Sheets file.
|
/// A Cascading Style Sheets file.
|
||||||
case css
|
case css
|
||||||
/// A HyperText Markup Language file.
|
|
||||||
case html
|
|
||||||
/// A JavaScript file.
|
/// A JavaScript file.
|
||||||
case js
|
case js
|
||||||
/// A Portable Network Graphics image.
|
/// A Portable Network Graphics image.
|
||||||
@@ -59,7 +51,6 @@ extension StaticFile {
|
|||||||
var contentType: String {
|
var contentType: String {
|
||||||
switch fileExtension {
|
switch fileExtension {
|
||||||
case .css: "text/css"
|
case .css: "text/css"
|
||||||
case .html: "text/html"
|
|
||||||
case .js: "text/javascript"
|
case .js: "text/javascript"
|
||||||
case .png: "image/png"
|
case .png: "image/png"
|
||||||
case .ico: "image/vnd.microsoft.icon"
|
case .ico: "image/vnd.microsoft.icon"
|
||||||
@@ -74,8 +65,6 @@ extension StaticFile {
|
|||||||
switch self {
|
switch self {
|
||||||
case .styleCSS: .css
|
case .styleCSS: .css
|
||||||
case .appJS: .js
|
case .appJS: .js
|
||||||
case .errorHTML,
|
|
||||||
.indexHTML: .html
|
|
||||||
case .faviconICO: .ico
|
case .faviconICO: .ico
|
||||||
case .iconPNG: .png
|
case .iconPNG: .png
|
||||||
case .iconSVG: .svg
|
case .iconSVG: .svg
|
||||||
@@ -88,11 +77,9 @@ extension StaticFile {
|
|||||||
var fileName: String {
|
var fileName: String {
|
||||||
switch self {
|
switch self {
|
||||||
case .appJS: "app"
|
case .appJS: "app"
|
||||||
case .errorHTML: "404"
|
|
||||||
case .faviconICO: "favicon"
|
case .faviconICO: "favicon"
|
||||||
case .iconPNG,
|
case .iconPNG,
|
||||||
.iconSVG: "icon"
|
.iconSVG: "icon"
|
||||||
case .indexHTML: "index"
|
|
||||||
case .robotsTXT: "robots"
|
case .robotsTXT: "robots"
|
||||||
case .siteWebmanifest: "site"
|
case .siteWebmanifest: "site"
|
||||||
case .styleCSS: "style"
|
case .styleCSS: "style"
|
||||||
@@ -103,18 +90,10 @@ extension StaticFile {
|
|||||||
///
|
///
|
||||||
/// This also matches the URL path the file is served at by `FileMiddleware`.
|
/// This also matches the URL path the file is served at by `FileMiddleware`.
|
||||||
var relativePath: String {
|
var relativePath: String {
|
||||||
let file = String(
|
let file = "\(fileName).\(fileExtension.rawValue)"
|
||||||
format: Constant.Format.file,
|
|
||||||
fileName,
|
|
||||||
fileExtension.rawValue
|
|
||||||
)
|
|
||||||
|
|
||||||
return subdirectory
|
return subdirectory
|
||||||
.map { .init(
|
.map { "\($0)/\(file)" } ?? file
|
||||||
format: Constant.Format.path,
|
|
||||||
$0,
|
|
||||||
file
|
|
||||||
)} ?? file
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Methods
|
// MARK: Methods
|
||||||
@@ -130,11 +109,7 @@ extension StaticFile {
|
|||||||
return relativePath
|
return relativePath
|
||||||
}
|
}
|
||||||
|
|
||||||
return .init(
|
return "\(basePath)/\(relativePath)"
|
||||||
format: Constant.Format.path,
|
|
||||||
basePath,
|
|
||||||
relativePath
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -155,12 +130,3 @@ private extension StaticFile {
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Constants
|
|
||||||
|
|
||||||
private enum Constant {
|
|
||||||
enum Format {
|
|
||||||
static let file = "%@.%@"
|
|
||||||
static let path = "%@/%@"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import Elementary
|
||||||
|
|
||||||
|
/// The HTML page rendered for a not-found response.
|
||||||
|
struct ErrorPage: HTMLDocument, Sendable {
|
||||||
|
|
||||||
|
// MARK: Document
|
||||||
|
|
||||||
|
/// The page's content.
|
||||||
|
var body: some HTML {
|
||||||
|
h1 { "Page Not Found" }
|
||||||
|
p { "Sorry, but the page you were trying to view does not exist." }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The metadata and inline styles placed in the document head.
|
||||||
|
var head: some HTML {
|
||||||
|
meta(.charset(.utf8))
|
||||||
|
meta(
|
||||||
|
.name(.viewport),
|
||||||
|
.content("width=device-width, initial-scale=1")
|
||||||
|
)
|
||||||
|
style { Self.styles }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The document language.
|
||||||
|
var lang: String { "en" }
|
||||||
|
|
||||||
|
/// The document title.
|
||||||
|
var title: String { "Page Not Found" }
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
|
private extension ErrorPage {
|
||||||
|
/// The inline CSS applied to the page.
|
||||||
|
static let styles = """
|
||||||
|
* {
|
||||||
|
line-height: 1.2;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
html {
|
||||||
|
color: #888;
|
||||||
|
display: table;
|
||||||
|
font-family: sans-serif;
|
||||||
|
height: 100%;
|
||||||
|
text-align: center;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
display: table-cell;
|
||||||
|
vertical-align: middle;
|
||||||
|
margin: 2em auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
color: #555;
|
||||||
|
font-size: 2em;
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
margin: 0 auto;
|
||||||
|
width: 280px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media only screen and (max-width: 280px) {
|
||||||
|
body, p {
|
||||||
|
width: 95%;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
font-size: 1.5em;
|
||||||
|
margin: 0 0 0.3em;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import Elementary
|
||||||
|
|
||||||
|
/// The website's landing page.
|
||||||
|
struct IndexPage: HTMLDocument, Sendable {
|
||||||
|
|
||||||
|
// MARK: Document
|
||||||
|
|
||||||
|
/// The page's content.
|
||||||
|
var body: some HTML {
|
||||||
|
p { "Hello world! This is HTML5 Boilerplate." }
|
||||||
|
script(.src("js/app.js")) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The metadata, stylesheet, icon, and manifest links placed in the document head.
|
||||||
|
var head: some HTML {
|
||||||
|
meta(.charset(.utf8))
|
||||||
|
meta(
|
||||||
|
.name(.viewport),
|
||||||
|
.content("width=device-width, initial-scale=1")
|
||||||
|
)
|
||||||
|
link(
|
||||||
|
.rel(.stylesheet),
|
||||||
|
.href("css/style.css")
|
||||||
|
)
|
||||||
|
link(
|
||||||
|
.rel(.icon),
|
||||||
|
.href("/favicon.ico"),
|
||||||
|
.custom(
|
||||||
|
name: "sizes",
|
||||||
|
value: "any"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
link(
|
||||||
|
.rel(.icon),
|
||||||
|
.href("/icon.svg"),
|
||||||
|
.custom(
|
||||||
|
name: "type",
|
||||||
|
value: "image/svg+xml"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
link(
|
||||||
|
.rel("apple-touch-icon"),
|
||||||
|
.href("icon.png")
|
||||||
|
)
|
||||||
|
link(
|
||||||
|
.rel("manifest"),
|
||||||
|
.href("site.webmanifest")
|
||||||
|
)
|
||||||
|
meta(
|
||||||
|
.name("theme-color"),
|
||||||
|
.content("#fafafa")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The document language.
|
||||||
|
var lang: String {
|
||||||
|
"en"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The document title.
|
||||||
|
var title: String { "" }
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import Hummingbird
|
||||||
|
import HummingbirdElementary
|
||||||
|
|
||||||
|
/// Serves the website's root routes.
|
||||||
|
///
|
||||||
|
/// The controller exposes its routes as a `RouteCollection` so they can be added to a router
|
||||||
|
/// (or a sub-group) by the application that composes it:
|
||||||
|
///
|
||||||
|
/// ```swift
|
||||||
|
/// router.addRoutes(RootController<AppRequestContext>().routes)
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// - Note: `Context` is the request context the routes are resolved against, and must match the
|
||||||
|
/// context of the router the routes are added to.
|
||||||
|
public struct RootController<Context: RequestContext> : Sendable{
|
||||||
|
|
||||||
|
// MARK: Initializers
|
||||||
|
|
||||||
|
/// Creates a root controller.
|
||||||
|
public init() {}
|
||||||
|
|
||||||
|
// MARK: Properties
|
||||||
|
|
||||||
|
/// The routes served by the controller.
|
||||||
|
///
|
||||||
|
/// Serves a `GET` request for the root path (`/`) by rendering the ``IndexPage``.
|
||||||
|
public var routes: RouteCollection<Context> {
|
||||||
|
let routes = RouteCollection(context: Context.self)
|
||||||
|
|
||||||
|
routes.get(
|
||||||
|
.Root.index,
|
||||||
|
use: index
|
||||||
|
)
|
||||||
|
|
||||||
|
return routes
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Helpers
|
||||||
|
|
||||||
|
private extension RootController {
|
||||||
|
|
||||||
|
// MARK: Methods
|
||||||
|
|
||||||
|
/// Handles a request for the landing page.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - request: the incoming request.
|
||||||
|
/// - context: the context the request is resolved against.
|
||||||
|
/// - Returns: an HTML response that renders the ``IndexPage``.
|
||||||
|
@Sendable
|
||||||
|
func index(
|
||||||
|
request: Request,
|
||||||
|
context: some RequestContext
|
||||||
|
) -> HTMLResponse {
|
||||||
|
.init {
|
||||||
|
IndexPage()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
|
extension RouterPath {
|
||||||
|
/// A namespace for the ``RootController`` route paths.
|
||||||
|
enum Root {
|
||||||
|
/// The path of the landing page.
|
||||||
|
static let index: RouterPath = "/"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,16 +3,7 @@ import Configuration
|
|||||||
extension ConfigValue {
|
extension ConfigValue {
|
||||||
/// A namespace for the HTTP server's default configuration values.
|
/// A namespace for the HTTP server's default configuration values.
|
||||||
public enum HTTP {
|
public enum HTTP {
|
||||||
/// The default host the server binds to.
|
|
||||||
public static let host: ConfigValue = .init(stringLiteral: "127.0.0.1")
|
|
||||||
/// The default port the server listens on.
|
|
||||||
public static let port: ConfigValue = .init(stringLiteral: "0")
|
|
||||||
/// The default server name.
|
/// The default server name.
|
||||||
public static let serverName: ConfigValue = .init(stringLiteral: .Server.name)
|
public static let serverName: ConfigValue = .init(stringLiteral: .Server.name)
|
||||||
}
|
}
|
||||||
/// A namespace for the logging default configuration values.
|
|
||||||
enum Log {
|
|
||||||
/// The default minimum log level.
|
|
||||||
public static let level: ConfigValue = .init(stringLiteral: "trace")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,45 +1,18 @@
|
|||||||
import Foundation
|
import Elementary
|
||||||
import Hummingbird
|
import Hummingbird
|
||||||
import NIOCore
|
import HummingbirdElementary
|
||||||
|
|
||||||
/// Serves a custom error page for requests that match neither a route nor a static file.
|
/// 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
|
/// 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
|
/// that bubbles up when no file exists for the requested path and responds with the rendered
|
||||||
/// error page and a `404 Not Found` status.
|
/// ``ErrorPage`` and a `404 Not Found` status.
|
||||||
public struct NotFoundMiddleware<Context: RequestContext> {
|
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
|
// MARK: Initializers
|
||||||
|
|
||||||
/// Creates a middleware that serves the error page (`404.html`) from the static files folder.
|
/// Creates a not-found middleware.
|
||||||
///
|
public init() {}
|
||||||
/// 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
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,6 +22,16 @@ extension NotFoundMiddleware: RouterMiddleware {
|
|||||||
|
|
||||||
// MARK: Functions
|
// MARK: Functions
|
||||||
|
|
||||||
|
/// Passes the request down the chain, rendering the error page if it results in a not-found
|
||||||
|
/// response.
|
||||||
|
///
|
||||||
|
/// Any error other than `.notFound` is rethrown unchanged.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - request: the incoming request.
|
||||||
|
/// - context: the context the request is resolved against.
|
||||||
|
/// - next: the next responder in the middleware chain.
|
||||||
|
/// - Returns: the downstream response, or the rendered ``ErrorPage`` with a `404 Not Found` status.
|
||||||
|
/// - Throws: any non-not-found error thrown downstream.
|
||||||
public func handle(
|
public func handle(
|
||||||
_ request: Request,
|
_ request: Request,
|
||||||
context: Context,
|
context: Context,
|
||||||
@@ -57,7 +40,6 @@ extension NotFoundMiddleware: RouterMiddleware {
|
|||||||
do {
|
do {
|
||||||
return try await next(request, context)
|
return try await next(request, context)
|
||||||
} catch let error {
|
} catch let error {
|
||||||
// Only intercept "not found"; let every other error propagate.
|
|
||||||
guard
|
guard
|
||||||
let responseError = error as? any HTTPResponseError,
|
let responseError = error as? any HTTPResponseError,
|
||||||
responseError.status == .notFound
|
responseError.status == .notFound
|
||||||
@@ -65,14 +47,14 @@ extension NotFoundMiddleware: RouterMiddleware {
|
|||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
|
|
||||||
var headers = HTTPFields()
|
return HTMLResponse(
|
||||||
|
status: .notFound
|
||||||
headers[.contentType] = StaticFile.errorHTML.contentType
|
) {
|
||||||
|
ErrorPage()
|
||||||
return Response(
|
}
|
||||||
status: .notFound,
|
.response(
|
||||||
headers: headers,
|
from: request,
|
||||||
body: .init(byteBuffer: page)
|
context: context
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,21 +27,16 @@ struct AppTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
func `landing page to be served at root`() async throws {
|
func `landing page to be served at root`() async throws {
|
||||||
let file: StaticFile = .indexHTML
|
|
||||||
let app = try await application(
|
|
||||||
reader: reader(
|
|
||||||
staticFilesPath: staticFilesPath
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
try await app.test(.router) { client in
|
try await app.test(.router) { client in
|
||||||
try await client.execute(
|
try await client.execute(
|
||||||
uri: "/",
|
uri: "/",
|
||||||
method: .get
|
method: .get
|
||||||
) { response in
|
) { response in
|
||||||
|
let body = String(buffer: response.body)
|
||||||
|
|
||||||
#expect(response.status == .ok)
|
#expect(response.status == .ok)
|
||||||
#expect(response.headers[.contentType] == file.contentType)
|
#expect(response.headers[.contentType]?.hasPrefix("text/html") == true)
|
||||||
#expect(response.body == data(of: file))
|
#expect(body.contains("Hello world!"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -50,12 +45,6 @@ struct AppTests {
|
|||||||
func `static files to be served`(
|
func `static files to be served`(
|
||||||
staticFile file: StaticFile
|
staticFile file: StaticFile
|
||||||
) async throws {
|
) async throws {
|
||||||
let app = try await application(
|
|
||||||
reader: reader(
|
|
||||||
staticFilesPath: staticFilesPath
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
try await app.test(.router) { client in
|
try await app.test(.router) { client in
|
||||||
try await client.execute(
|
try await client.execute(
|
||||||
uri: "/\(file.relativePath)",
|
uri: "/\(file.relativePath)",
|
||||||
@@ -69,21 +58,16 @@ struct AppTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
func `error page to be served when not found`() async throws {
|
func `error page to be served when not found`() async throws {
|
||||||
let file: StaticFile = .errorHTML
|
|
||||||
let app = try await application(
|
|
||||||
reader: reader(
|
|
||||||
staticFilesPath: staticFilesPath
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
try await app.test(.router) { client in
|
try await app.test(.router) { client in
|
||||||
try await client.execute(
|
try await client.execute(
|
||||||
uri: "/this-path-does-not-exist",
|
uri: "/this-path-does-not-exist",
|
||||||
method: .get
|
method: .get
|
||||||
) { response in
|
) { response in
|
||||||
|
let body = String(buffer: response.body)
|
||||||
|
|
||||||
#expect(response.status == .notFound)
|
#expect(response.status == .notFound)
|
||||||
#expect(response.headers[.contentType] == file.contentType)
|
#expect(response.headers[.contentType]?.hasPrefix("text/html") == true)
|
||||||
#expect(response.body == data(of: file))
|
#expect(body.contains("Page Not Found"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -94,28 +78,28 @@ struct AppTests {
|
|||||||
|
|
||||||
private extension AppTests {
|
private extension AppTests {
|
||||||
|
|
||||||
|
// MARK: Computed
|
||||||
|
|
||||||
|
var app: some ApplicationProtocol {
|
||||||
|
get async {
|
||||||
|
await application(
|
||||||
|
reader: reader(
|
||||||
|
staticFilesPath: staticFilesPath
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: Methods
|
// MARK: Methods
|
||||||
|
|
||||||
func data(
|
|
||||||
of file: StaticFile
|
|
||||||
) -> ByteBuffer {
|
|
||||||
let url = URL(fileURLWithPath: file.path(relativeTo: staticFilesPath))
|
|
||||||
|
|
||||||
guard let data = try? Data(contentsOf: url) else {
|
|
||||||
return ByteBuffer()
|
|
||||||
}
|
|
||||||
|
|
||||||
return ByteBuffer(bytes: data)
|
|
||||||
}
|
|
||||||
|
|
||||||
func reader(
|
func reader(
|
||||||
staticFilesPath: String
|
staticFilesPath: String
|
||||||
) -> ConfigReader {
|
) -> ConfigReader {
|
||||||
ConfigReader(providers: [
|
ConfigReader(providers: [
|
||||||
InMemoryProvider(values: [
|
InMemoryProvider(values: [
|
||||||
.HTTP.host: .HTTP.host,
|
.HTTP.host: "127.0.0.1",
|
||||||
.HTTP.port: .HTTP.port,
|
.HTTP.port: "0",
|
||||||
.Log.level: .Log.level,
|
.Log.level: "trace",
|
||||||
.Path.staticFiles: .init(stringLiteral: staticFilesPath),
|
.Path.staticFiles: .init(stringLiteral: staticFilesPath),
|
||||||
])
|
])
|
||||||
])
|
])
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ struct StaticFileTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
func `all cases`() {
|
func `all cases`() {
|
||||||
#expect(File.allCases.count == 9)
|
#expect(File.allCases.count == 7)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -95,44 +95,36 @@ private extension StaticFileTests {
|
|||||||
|
|
||||||
static let contentTypes: [String] = [
|
static let contentTypes: [String] = [
|
||||||
"text/javascript",
|
"text/javascript",
|
||||||
"text/html",
|
|
||||||
"image/vnd.microsoft.icon",
|
"image/vnd.microsoft.icon",
|
||||||
"image/png",
|
"image/png",
|
||||||
"image/svg+xml",
|
"image/svg+xml",
|
||||||
"text/html",
|
|
||||||
"text/plain",
|
"text/plain",
|
||||||
"application/manifest+json",
|
"application/manifest+json",
|
||||||
"text/css"
|
"text/css"
|
||||||
]
|
]
|
||||||
static let fileExtensions: [FileExtension] = [
|
static let fileExtensions: [FileExtension] = [
|
||||||
.js,
|
.js,
|
||||||
.html,
|
|
||||||
.ico,
|
.ico,
|
||||||
.png,
|
.png,
|
||||||
.svg,
|
.svg,
|
||||||
.html,
|
|
||||||
.txt,
|
.txt,
|
||||||
.webmanifest,
|
.webmanifest,
|
||||||
.css
|
.css
|
||||||
]
|
]
|
||||||
static let fileNames: [String] = [
|
static let fileNames: [String] = [
|
||||||
"app",
|
"app",
|
||||||
"404",
|
|
||||||
"favicon",
|
"favicon",
|
||||||
"icon",
|
"icon",
|
||||||
"icon",
|
"icon",
|
||||||
"index",
|
|
||||||
"robots",
|
"robots",
|
||||||
"site",
|
"site",
|
||||||
"style"
|
"style"
|
||||||
]
|
]
|
||||||
static let relativePaths: [String] = [
|
static let relativePaths: [String] = [
|
||||||
"js/app.js",
|
"js/app.js",
|
||||||
"404.html",
|
|
||||||
"favicon.ico",
|
"favicon.ico",
|
||||||
"icon.png",
|
"icon.png",
|
||||||
"icon.svg",
|
"icon.svg",
|
||||||
"index.html",
|
|
||||||
"robots.txt",
|
"robots.txt",
|
||||||
"site.webmanifest",
|
"site.webmanifest",
|
||||||
"css/style.css"
|
"css/style.css"
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import Elementary
|
||||||
|
import Testing
|
||||||
|
|
||||||
|
@testable import WebsiteCore
|
||||||
|
|
||||||
|
@Suite("ErrorPage page")
|
||||||
|
struct ErrorPageTests {
|
||||||
|
|
||||||
|
// MARK: Functional tests
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func `renders its markup`() {
|
||||||
|
let html = ErrorPage().render()
|
||||||
|
|
||||||
|
#expect(html.contains("<!DOCTYPE html>"))
|
||||||
|
#expect(html.contains("Page Not Found"))
|
||||||
|
#expect(html.contains("does not exist"))
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import Elementary
|
||||||
|
import Testing
|
||||||
|
|
||||||
|
@testable import WebsiteCore
|
||||||
|
|
||||||
|
@Suite("IndexPage page")
|
||||||
|
struct IndexPageTests {
|
||||||
|
|
||||||
|
// MARK: Functional tests
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func `renders its markup`() {
|
||||||
|
let html = IndexPage().render()
|
||||||
|
|
||||||
|
#expect(html.contains("<!DOCTYPE html>"))
|
||||||
|
#expect(html.contains("Hello world!"))
|
||||||
|
#expect(html.contains("css/style.css"))
|
||||||
|
#expect(html.contains("js/app.js"))
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import Hummingbird
|
||||||
|
import HummingbirdTesting
|
||||||
|
import NIOCore
|
||||||
|
import Testing
|
||||||
|
|
||||||
|
@testable import WebsiteCore
|
||||||
|
|
||||||
|
@Suite("RootController controller")
|
||||||
|
struct RootControllerTests {
|
||||||
|
|
||||||
|
// MARK: Constants
|
||||||
|
|
||||||
|
private let app: Application = .init(router: {
|
||||||
|
let router = Router()
|
||||||
|
|
||||||
|
router.addRoutes(RootController<BasicRequestContext>().routes)
|
||||||
|
|
||||||
|
return router
|
||||||
|
}())
|
||||||
|
|
||||||
|
// MARK: Functional tests
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func `serves the landing page at the root path`() async throws {
|
||||||
|
try await app.test(.router) { client in
|
||||||
|
try await client.execute(
|
||||||
|
uri: "/",
|
||||||
|
method: .get
|
||||||
|
) { response in
|
||||||
|
let body = String(buffer: response.body)
|
||||||
|
|
||||||
|
#expect(response.status == .ok)
|
||||||
|
#expect(response.headers[.contentType] == "text/html; charset=utf-8")
|
||||||
|
#expect(body.contains("Hello world!"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import Hummingbird
|
||||||
|
import HummingbirdTesting
|
||||||
|
import NIOCore
|
||||||
|
import Testing
|
||||||
|
|
||||||
|
@testable import WebsiteCore
|
||||||
|
|
||||||
|
@Suite("NotFoundMiddleware middleware")
|
||||||
|
struct NotFoundMiddlewareTests {
|
||||||
|
|
||||||
|
// MARK: Constants
|
||||||
|
|
||||||
|
private let app: Application = .init(router: {
|
||||||
|
let router = Router()
|
||||||
|
|
||||||
|
router.addMiddleware {
|
||||||
|
NotFoundMiddleware()
|
||||||
|
}
|
||||||
|
|
||||||
|
router.get("hello") { _, _ in
|
||||||
|
"Hello!"
|
||||||
|
}
|
||||||
|
|
||||||
|
router.get("boom") { _, _ -> String in
|
||||||
|
throw HTTPError(.badRequest)
|
||||||
|
}
|
||||||
|
|
||||||
|
return router
|
||||||
|
}())
|
||||||
|
|
||||||
|
// MARK: Functional tests
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func `renders the error page for an unmatched request`() async throws {
|
||||||
|
try await app.test(.router) { client in
|
||||||
|
try await client.execute(
|
||||||
|
uri: "/this-path-does-not-exist",
|
||||||
|
method: .get
|
||||||
|
) { response in
|
||||||
|
let body = String(buffer: response.body)
|
||||||
|
|
||||||
|
#expect(response.status == .notFound)
|
||||||
|
#expect(response.headers[.contentType] == "text/html; charset=utf-8")
|
||||||
|
#expect(body.contains("Page Not Found"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func `passes a matched response through untouched`() async throws {
|
||||||
|
try await app.test(.router) { client in
|
||||||
|
try await client.execute(
|
||||||
|
uri: "/hello",
|
||||||
|
method: .get
|
||||||
|
) { response in
|
||||||
|
#expect(response.status == .ok)
|
||||||
|
#expect(response.body == ByteBuffer(string: "Hello!"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func `rethrows a non-not-found error unchanged`() async throws {
|
||||||
|
try await app.test(.router) { client in
|
||||||
|
try await client.execute(
|
||||||
|
uri: "/boom",
|
||||||
|
method: .get
|
||||||
|
) { response in
|
||||||
|
let body = String(buffer: response.body)
|
||||||
|
|
||||||
|
#expect(response.status == .badRequest)
|
||||||
|
#expect(!body.contains("Page Not Found"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user