Skip to content

Web frameworks ​

Responding with a render from axum or actix-web.

Three optional features turn renders into HTTP responses:

FeatureWhat it adds
axumIntoResponse for Html and HtmlStream
actix-webResponder for both, and From both for HttpResponse
streamHtmlStream alone, a Stream of byte chunks for any other server; both features above include it
toml
[dependencies]
ferrovue = { version = "0.16", features = ["axum"] }

Every response is 200 OK with Content-Type: text/html; charset=utf-8; each framework's own way of changing the status applies.

A component ​

A generated html() or island() is an Html, and with the axum feature an IntoResponse. A handler builds the props and returns into_html(props) or into_island(props), the forms that hold their props: the component is rendered once the handler has returned, into the response's body.

rust
use axum::Router;
use axum::extract::Path;
use axum::response::IntoResponse;
use axum::routing::get;

async fn hello(Path(name): Path<String>) -> impl IntoResponse {
    greeting::into_html(greeting::Props::new(name))
}

// The island alone, for a client that swaps it into a page it already shows.
async fn hello_island(Path(name): Path<String>) -> impl IntoResponse {
    greeting::into_island(greeting::Props::new(name))
}

let app: Router = Router::new()
    .route("/hello/{name}", get(hello))
    .route("/islands/hello/{name}", get(hello_island));

The response outlives the handler, so the Html must borrow nothing from it: props of owned strings (Props::new(name) with a String) or 'static ones. html(&props) and island(&props) borrow the props, and serve as a response when the props outlive the handler, such as a static. A component that takes slots, the route, stores, translations or teleports has only html, which borrows them as well; render it into the page's String and respond with that, as below.

A page ​

A whole page is usually written into one String: the document's head, the layout's render with the route's page in its <RouterView> slot, the stores' state, the client's script. Make it an HtmlStream to send it. A render without holes is sent whole, with its Content-Length; for another status than 200 OK, respond with the status beside it:

rust
use axum::http::{StatusCode, Uri};
use axum::response::{IntoResponse, Response};
use ferrovue::web::HtmlStream;

async fn not_found(uri: Uri) -> Response {
    let mut page = String::from("<!doctype html><html><body><h1>Nothing at <code>");
    ferrovue::core::escape_into(&mut page, uri.path());
    page.push_str("</code></h1></body></html>");
    (StatusCode::NOT_FOUND, HtmlStream::new(page)).into_response()
}

let app: axum::Router = axum::Router::new().fallback(not_found);

A page from the fallback ​

A fallback that renders whatever path the router resolves also serves paths a browser reads as another host. axum hands the fallback //evil.example/x as it arrived, and on that page every relative link, ?page=2, #top or sibling, resolves to an href starting //evil.example/, as vue-router resolves it in the browser. A \ reads as a / to the browser, so /\evil.example/x does the same. Answer such a path before resolving it:

rust
use std::sync::LazyLock;

use axum::http::{StatusCode, Uri};
use axum::response::{IntoResponse, Response};
use ferrovue::router::Router;

static ROUTER: LazyLock<Router> = LazyLock::new(|| Router::new(&["/", "/:rest(.*)"]));

async fn page(uri: Uri) -> Response {
    let path = uri.path();
    if path.starts_with("//") || path.contains('\\') {
        return StatusCode::NOT_FOUND.into_response();
    }
    let route = ROUTER.at(uri.path_and_query().map_or(path, |p| p.as_str()));
    route.link("?page=2").href.into_response()
}

linkRoutes and linkRouter never hand navigate a link to another host: such a navigation fails with an error. The hrefs of the page the server sends are written as vue-router writes them, so the check above is what keeps them on the site.

A page streamed ​

A page rendered with holes (streaming) is sent in pieces. Give HtmlStream the whole render and a future for each hole, in the order the holes appear: the markup up to the first hole goes out at once, and each hole's content, then the markup after it, as soon as that hole and every one before it are ready. The futures all run from the start, so the page ends when the slowest one does.

rust
use std::time::Duration;

use axum::extract::Path;
use axum::response::{IntoResponse, Response};
use ferrovue::{page::hole, render::slot_into, web::HtmlStream};

/// The reviews of a book, from a slow service.
async fn review_count(_id: &str) -> i64 {
    tokio::time::sleep(Duration::from_millis(10)).await;
    3
}

async fn book(Path(id): Path<String>) -> Response {
    // The book's page, rendered at once with a hole where the reviews go: here the slot of a
    // generated component, `Slots { reviews: Some(ferrovue::page::hole()), .. }`.
    let mut page = String::from("<!doctype html><html><body><h1>");
    ferrovue::core::escape_into(&mut page, &id);
    page.push_str("</h1><section>");
    slot_into(&mut page, Some(hole()), None);
    page.push_str("</section></body></html>");

    // The hole's content: an island, rendered when its data is ready. The future owns what it
    // reads, as the response outlives the handler.
    let reviews = async move {
        let props = reviews::Props { count: review_count(&id).await };
        reviews::into_island(props).into_string()
    };
    HtmlStream::new(page).hole(reviews).into_response()
}

HtmlStream::holes takes the futures from an iterator, when every hole's content comes from the same function; hole takes one at a time, each of its own type. A hole given no future is left empty, and a future beyond the last hole is never run. A future must be Send and own what it reads (an async move block, an Arc of shared state cloned into it), as the body is sent after the handler returns.

The repository's examples/fullstack serves every page this way, its book pages with their reviews in a hole, and the reviews alone, at /books/{id}/reviews, from into_island.

actix-web ​

The same with the actix-web feature: Html and HtmlStream are Responders, and either becomes an HttpResponse with .into().

rust
use actix_web::http::StatusCode;
use actix_web::{App, Responder, web};
use ferrovue::web::HtmlStream;

async fn hello(name: web::Path<String>) -> impl Responder {
    greeting::into_html(greeting::Props::new(name.into_inner()))
}

async fn not_found() -> impl Responder {
    let page = String::from("<!doctype html><html><body><h1>Not found</h1></body></html>");
    HtmlStream::new(page).customize().with_status(StatusCode::NOT_FOUND)
}

let app = App::new()
    .route("/hello/{name}", web::get().to(hello))
    .default_service(web::to(not_found));

Other servers ​

With the stream feature alone, HtmlStream is a futures_core::Stream of Result<bytes::Bytes, Infallible>, which is what a Rust HTTP server makes a streamed body from: hyper's StreamBody, once each chunk is mapped to a frame, or any framework's equivalent. Its pieces are slices of the one render, never copied.