#brotli #rocket #gzip #format

rocket_async_compression

Response compression in both gzip and brotli formats for the Rocket webserver using the async-compression library

10 releases (5 breaking)

0.6.1 Sep 3, 2024
0.6.0 Apr 10, 2024
0.5.1 Nov 19, 2023
0.5.0 Jun 15, 2023
0.1.0 Nov 2, 2021

#122 in Compression

Download history 26/week @ 2024-07-31 19/week @ 2024-08-07 29/week @ 2024-08-14 87/week @ 2024-08-21 112/week @ 2024-08-28 300/week @ 2024-09-04 135/week @ 2024-09-11 204/week @ 2024-09-18 310/week @ 2024-09-25 268/week @ 2024-10-02 213/week @ 2024-10-09 186/week @ 2024-10-16 179/week @ 2024-10-23 284/week @ 2024-10-30 387/week @ 2024-11-06 137/week @ 2024-11-13

1,041 downloads per month
Used in thangail

MIT license

24KB
400 lines

Rocket Async Compression

This library provides response compression in both gzip and brotli formats for Rocket using the async-compression library.

I'd love to get this merged into Rocket itself eventually since I think it would be a very useful addition that I myself can barely live without in a webserver.

Installation

Add this to Cargo.toml:

[dependencies]
rocket = "0.5"
rocket_async_compression = "0.6"

Usage

The following example will enable compression only when the crate is built in release mode. Compression can be very slow when using unoptimized debug builds while developing locally.

#[macro_use]
extern crate rocket;

use rocket_async_compression::Compression;

#[launch]
async fn rocket() -> _ {
    let server = rocket::build()
        .mount("/", routes![...]);

    if cfg!(debug_assertions) {
        server
    } else {
        server.attach(Compression::fairing())
    }
}

Cached Compression

When serving static files, it can be useful to avoid the work of compressing the same files repeatedly for each request. This crate provides an alternative CachedCompression fairing which stores cached responses in memory and uses those when available.

Note that cached responses do not expire and will be held in memory for the life of the program. You should only use this fairing for compressing static files that will not change while the server is running.

#[macro_use]
extern crate rocket;

use rocket::fs::{relative, FileServer};
use rocket_async_compression::CachedCompression;

#[launch]
async fn rocket() -> _ {
    rocket::build()
        .mount(
            "/",
            FileServer::from(relative!("static")),
        )
        .attach(CachedCompression::path_suffix_fairing(vec![".js", ".css", ".html", ".wasm"]))
}

Dependencies

~22–53MB
~1M SLoC