Localization support for the Website service (#10)

This PR contains the work done to introduce server-side localization support to the **Website** service so the landing and error pages are served in the visitor's negotiated language, backed by a new reusable Localization package.

To provide further details about the work:

* Created the _Localization_ package — a bundle-bound `Localize` method and a `LanguageList` type.
* Language negotiation — `NegotiateLanguage` method picks the best supported language from the request's _Accept-Language_ header (falling back to the default); the `LocalizationMiddleware` middleware resolves it per request and stores it on a new `LocalizedRequestContext` / `WebsiteRequestContext` context.
* Localized responses — `LocalizedHTMLCollectionResponse` pre-renders each page once per language and caches the bytes (with `Content-Language` + `Vary: Accept-Language`), reused by the  `RootController` controller and `NotFoundMiddleware` middleware.
* The `CachedHTMLResponse` response gained custom-header support.
* Localized pages — the `IndexPage` and `ErrorPage` pages now resolve their strings via `Localize` method;
* Added `Localizable.xcstrings` catalogs.
* Wired the `LocalizationMiddleware` middlewaer into the router.

Reviewed-on: rock-n-code/loud-amsterdam#10
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:
2026-06-29 23:08:36 +00:00
committed by javier
parent 847058d642
commit 6c66ea74cc
24 changed files with 858 additions and 49 deletions
@@ -0,0 +1,42 @@
import Hummingbird
import Localization
/// A request context that carries the language negotiated for the request.
///
/// ``LocalizationMiddleware`` resolves the visitor's preferred language from the `Accept-Language`
/// header and stores it here, so downstream controllers and middleware can serve the matching
/// localization without re-reading the header.
public protocol LocalizedRequestContext: RequestContext {
// MARK: Properties
/// The language identifier negotiated for the request.
var language: String { get set }
}
// MARK: - Context
/// The website's request context.
///
/// Extends the core request storage with the negotiated language, defaulting to the default
/// supported language until ``LocalizationMiddleware`` resolves it from the request.
public struct WebsiteRequestContext: LocalizedRequestContext {
// MARK: Properties
/// The core request context storage Hummingbird requires.
public var coreContext: CoreRequestContextStorage
/// The language identifier negotiated for the request.
public var language: String
// MARK: Initializers
/// Creates a request context for the given source.
/// - Parameter source: the source the context is initialized from.
public init(source: Source) {
self.coreContext = .init(source: source)
self.language = LanguageList(bundle: .module).default
}
}
@@ -11,25 +11,26 @@ import Hummingbird
///
/// - 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 {
public struct RootController<Context: LocalizedRequestContext>: Sendable {
// MARK: Properties
/// The landing page, rendered once at initialization and reused for every request.
private let cache: CachedHTMLResponse
/// The landing page, rendered once per supported language and reused for every request.
private let responses: LocalizedHTMLCollectionResponse
// MARK: Initializers
/// Creates a root controller.
public init() {
self.cache = .init(IndexPage())
self.responses = .init { IndexPage(locale: $0) }
}
// MARK: Computed
/// The routes served by the controller.
///
/// Serves a `GET` request for the root path (`/`) by rendering the ``IndexPage``.
/// Serves a `GET` request for the root path (`/`) by rendering the ``IndexPage`` in the
/// language negotiated for the request.
public var routes: RouteCollection<Context> {
let routes = RouteCollection(context: Context.self)
@@ -50,16 +51,19 @@ private extension RootController {
// MARK: Methods
/// Handles a request for the landing page.
///
/// Renders the ``IndexPage`` in the language stored on the context by ``LocalizationMiddleware``,
/// falling back to the default language.
/// - Parameters:
/// - request: the incoming request.
/// - context: the context the request is resolved against.
/// - Returns: the cached ``IndexPage`` response.
/// - Returns: the cached ``IndexPage`` response for the context's language.
@Sendable
func index(
request: Request,
context: some RequestContext
context: Context
) -> Response {
cache.response()
responses.response(for: context.language)
}
}
@@ -0,0 +1,56 @@
import HTTPTypes
import Hummingbird
import Localization
/// Resolves the visitor's preferred language and records it on the request context.
///
/// Placed ahead of the localized responders in the middleware chain, it reads the request's
/// `Accept-Language` header, negotiates the best supported match (falling back to the default
/// language), and stores it on the context's ``LocalizedRequestContext/language``.
///
/// The request is otherwise passed through untouched the URL and routing are not affected so
/// each page is served at its existing path and varies its content by header.
public struct LocalizationMiddleware<Context: LocalizedRequestContext> {
// MARK: Properties
/// Negotiates the request's language from its `Accept-Language` header.
private let negotiate: NegotiateLanguage
// MARK: Initializers
/// Creates a localization middleware.
public init() {
self.negotiate = .init()
}
}
// MARK: - RouterMiddleware
extension LocalizationMiddleware: RouterMiddleware {
// MARK: Functions
/// Negotiates the request's language and records it on the context before passing it down.
/// - 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.
/// - Throws: any error thrown downstream.
public func handle(
_ request: Request,
context: Context,
next: (Request, Context) async throws -> Response
) async throws -> Response {
var context = context
context.language = negotiate(
forAcceptLanguage: request.headers[.acceptLanguage]
)
return try await next(request, context)
}
}
@@ -4,22 +4,24 @@ import Hummingbird
///
/// 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 rendered
/// ``ErrorPage`` and a `404 Not Found` status.
public struct NotFoundMiddleware<Context: RequestContext> {
/// ``ErrorPage`` and a `404 Not Found` status. The page is served in the language stored on the
/// context by ``LocalizationMiddleware``, falling back to the default language.
public struct NotFoundMiddleware<Context: LocalizedRequestContext> {
// MARK: Properties
/// The error page, rendered once at initialization and reused for every not-found response.
private let cache: CachedHTMLResponse
/// The error page, rendered once per supported language and reused for every not-found response.
private let responses: LocalizedHTMLCollectionResponse
// MARK: Initializers
/// Creates a not-found middleware.
public init() {
self.cache = .init(
status: .notFound,
ErrorPage()
)
self.responses = .init(
status: .notFound
) {
ErrorPage(locale: $0)
}
}
}
@@ -56,7 +58,9 @@ extension NotFoundMiddleware: RouterMiddleware {
throw error
}
return cache.response()
return responses.response(
for: context.language
)
}
}