Skip to main content

HtmlRewriter

Struct HtmlRewriter 

Source
pub struct HtmlRewriter { /* private fields */ }
Expand description

A trillium [Handler] that rewrites HTML response bodies with lol-html, using lol-async.

It wraps the response produced by other handlers: in before_send it inspects the outgoing Content-Type and, if the mime subtype is html (e.g. text/html), replaces the response body with a streaming rewrite driven by the Settings returned from the settings function passed to new, new_with_conn, or new_async. Responses with any other content type (or none) are passed through unchanged.

Implementations§

Source§

impl HtmlRewriter

Source

pub fn new( f: impl Fn() -> Settings<'static, 'static> + Send + Sync + 'static, ) -> Self

Construct a new html rewriter that applies the same rewrite to every response.

A function — rather than a Settings value — is required because lol-html’s content handlers are single-use; it is invoked once per rewritten response to produce a fresh set of handlers. Build the settings with [Settings::new_send()] as the base (its handlers are Send, as required here) and populate element_content_handlers / document_content_handlers. See [lol_async::html::Settings] and the lol-html docs for the full rewriting API.

HtmlRewriter::new(|| {
    Settings::new_send().append_element_content_handler(element!("body", |el| {
        el.prepend(r#"<script src="/analytics.js"></script>"#, ContentType::Html);
        Ok(())
    }))
});

To vary the rewrite based on the request or response, see new_with_conn; to await async work while building the settings, see new_async.

Source

pub fn new_with_conn( f: impl Fn(&Conn) -> Settings<'static, 'static> + Send + Sync + 'static, ) -> Self

Construct a new html rewriter from a function that builds Settings for a given [Conn].

The function receives the conn whose response is about to be rewritten, so the rewrite can depend on the request path, headers, or state. Like all three constructors, the function is invoked once per rewritten response — see new for why a function is required and how to build the settings — and it only runs for responses that are actually rewritten, so no work is done for non-html responses.

Data read from the conn must be moved into the content handlers, which outlive the conn borrow:

HtmlRewriter::new_with_conn(|conn| {
    let path = conn.path().to_string();
    Settings::new_send().append_element_content_handler(element!("head", move |el| {
        el.prepend(&format!(r#"<link rel="canonical" href="{path}">"#), ContentType::Html);
        Ok(())
    }))
});

To await async work while building the settings, see new_async.

Source

pub fn new_async<F>(f: F) -> Self
where F: for<'a> SettingsFn<'a>,

Construct a new html rewriter from an async function that builds Settings for a given [Conn].

Like new_with_conn, the function receives the conn whose response is about to be rewritten; because it is async, it can also await while borrowing the conn, so the settings can incorporate the result of async work such as a database query or an http request. Like all three constructors, the function is invoked once per rewritten response — see new for why a function is required and how to build the settings.

§Supported forms

The parameter type annotation : &Conn is required on closures — inference cannot supply it through the higher-ranked SettingsFn bound.

An async closure (or equivalently a named async fn(&Conn) -> Settings<'static, 'static>) may borrow the conn across .await, but must not capture its environment:

HtmlRewriter::new_async(async |conn: &Conn| {
    let url = canonical_url(conn.path()).await;
    Settings::new_send().append_element_content_handler(element!("head", move |el| {
        el.prepend(&format!(r#"<link rel="canonical" href="{url}">"#), ContentType::Html);
        Ok(())
    }))
});

To use captured state (a client handle, configuration, …), write a plain closure that clones what it needs — from its environment and from the conn — into an async block it returns. In this form the future cannot borrow the conn:

HtmlRewriter::new_async(move |conn: &Conn| {
    let client = client.clone();
    let path = conn.path().to_string();
    async move {
        let banner = client.fetch_banner(path).await;
        Settings::new_send().append_element_content_handler(element!("body", move |el| {
            el.prepend(&banner, ContentType::Html);
            Ok(())
        }))
    }
});

Note that in either form, data destined for the content handlers must be moved into them, as they outlive the settings-building future.

Trait Implementations§

Source§

impl Debug for HtmlRewriter

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Handler for HtmlRewriter

Source§

async fn before_send(&self, conn: Conn) -> Conn

Performs any final modifications to this conn after all handlers have been run. Although this is a slight deviation from the simple conn->conn->conn chain represented by most Handlers, it provides an easy way for libraries to effectively inject a second handler into a response chain. This is useful for loggers that need to record information both before and after other handlers have run, as well as database transaction handlers and similar library code. Read more
§

fn run(&self, conn: Conn) -> impl Future<Output = Conn> + Send

Executes this handler, performing any modifications to the Conn that are desired.
§

fn init(&mut self, info: &mut Info) -> impl Future<Output = ()> + Send

Performs one-time async set up on a mutable borrow of the Handler before the server starts accepting requests. This allows a Handler to be defined in synchronous code but perform async setup such as establishing a database connection or fetching some state from an external source. This is optional, and chances are high that you do not need this. Read more
§

fn has_upgrade(&self, upgrade: &Upgrade) -> bool

predicate function answering the question of whether this Handler would like to take ownership of the negotiated Upgrade. If this returns true, you must implement [Handler::upgrade]. The first handler that responds true to this will receive ownership of the [trillium::Upgrade][crate::Upgrade] in a subsequent call to [Handler::upgrade]
§

fn upgrade(&self, upgrade: Upgrade) -> impl Future<Output = ()> + Send

This will only be called if the handler reponds true to [Handler::has_upgrade] and will only be called once for this upgrade. There is no return value, and this function takes exclusive ownership of the underlying transport once this is called. You can downcast the transport to whatever the source transport type is and perform any non-http protocol communication that has been negotiated. You probably don’t want this unless you’re implementing something like websockets. Please note that for many transports such as TcpStreams, dropping the transport (and therefore the Upgrade) will hang up / disconnect.
§

fn name(&self) -> Cow<'static, str>

Customize the name of your handler. This is used in Debug implementations. The default is the type name of this handler.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.