Skip to main content

Module html_rewrite

Module html_rewrite 

Available on crate features html and http and std only.
Expand description

Middleware that rewrites text/html response bodies on the fly, using rama’s streaming HTML rewriter (crate::protocols::html::rewrite).

HtmlRewriteLayer wraps a service and, for each response, checks the Content-Type: a text/html body (that is not content-encoded) is piped through an HtmlRewriter as it streams, applying a handler to matched elements; anything else is forwarded unchanged. Because rewriting changes the body length, the layer drops the now-stale Content-Length.

The body adapter, HtmlRewriteBody, is also usable on its own — e.g. composed with MapResponseBodyLayer — when you already handle the header concerns yourself.

§Handlers

The handler is any type implementing ElementContentHandler. The layer requires it to be Clone (it is cloned per response, so each response rewrites with fresh handler state) and Send. A plain data struct fits naturally — no Rc<RefCell> / Arc<Mutex> / SyncWrapper ceremony, since the rewriter is owned and only touched through &mut self while the body is polled.

When the handler accumulates state, recover it once the body finishes via HtmlRewriteBody::on_end.

§Documents and fragments

By default each body is parsed as a full document, the way a browser parses a page it navigates to (ScopeMode::Browser), which keeps a hostile server from ending a matched element early with markup browsers ignore. Responses that carry fragments for insertion into another element (<tr> rows, partial templates, …) are not documents; rewrite those with ScopeMode::NearestMatch via with_scope_mode. The mode is not guessed from the content: a server choosing which parse the rewriter follows is exactly what the default guards against.

§Encoding

The rewriter sees raw bytes, so a compressed (Content-Encoding) body is skipped. Place this layer after a decompression layer if you need to rewrite compressed responses. Charset is assumed UTF-8 (the rewriter is byte-faithful; a leading byte order mark passes through untouched).

Structs§

HtmlRewrite
Rewrites the text/html response bodies of the underlying service, using rama’s streaming HtmlRewriter.
HtmlRewriteBody
A response body that feeds the inner body’s bytes through an HtmlRewriter, emitting rewritten chunks as they become available.
HtmlRewriteLayer
Layer that applies HtmlRewrite to the responses of the wrapped service.