[][src]Module roa::compress

The compress module of roa. This module provides a middleware Compress.

Example

use roa::compress::{Compress, Level};
use roa::body::PowerBody;
use roa::core::{App, StatusCode, header::ACCEPT_ENCODING};
use async_std::task::spawn;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    pretty_env_logger::init();
    let (addr, server) = App::new(())
        .gate_fn(|ctx, next| async move {
            next().await?;
            // compress body to 202 bytes in gzip with quantity Level::Fastest.
            ctx.resp_mut().await.on_finish(|body| assert_eq!(202, body.consumed()));
            Ok(())
        })
        .gate(Compress(Level::Fastest))
        .end(|ctx| async move {
            // the size of assets/welcome.html is 236 bytes.
            ctx.resp_mut().await.on_finish(|body| assert_eq!(236, body.consumed()));
            ctx.write_file("assets/welcome.html").await
        })
        .run_local()?;
    spawn(server);
    let client = reqwest::Client::builder().gzip(true).build()?;
    let resp = client
        .get(&format!("http://{}", addr))
        .header(ACCEPT_ENCODING, "gzip")
        .send()
        .await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

Structs

Compress

A middleware to negotiate with client and compress response body automatically, supports gzip, deflate, brotli, zstd and identity.

Enums

Level

Level of compression data should be compressed with.