#http-response #axum #cache #middleware #http #http-request

axum-response-cache

Axum layer for caching HTTP responses of the wrapped server

3 releases

new 0.1.2 Dec 9, 2024
0.1.1 Oct 18, 2024
0.1.0 Oct 7, 2024

#389 in Caching

Download history 280/week @ 2024-10-07 204/week @ 2024-10-14 47/week @ 2024-10-21 28/week @ 2024-10-28 61/week @ 2024-11-04 30/week @ 2024-11-11 47/week @ 2024-11-18 31/week @ 2024-11-25 59/week @ 2024-12-02

169 downloads per month

MIT license

34KB
531 lines

This library provides Axum middleware that caches HTTP responses to the incoming requests based on their HTTP method and path.

The main struct is CacheLayer. It can be created with any cache that implements two traits from the cached crate: cached::Cached and cached::CloneCached.

The current version of CacheLayer is compatible only with services accepting Axum’s Request<Body> and returning axum::response::Response, thus it is not compatible with non-Axum tower services.

It’s possible to configure the layer to re-use an old expired response in case the wrapped service fails to produce a new successful response.

Only successful responses are cached (responses with status codes outside of the [200-299] range are passed-through or ignored).

The cache limits maximum size of the response’s body (128 MB by default).

Example

To cache a response over a specific route, just wrap it in a CacheLayer:

use axum::{Router, extract::Path, routing::get};
use axum_response_cache::CacheLayer;

#[tokio::main]
async fn main() {
    let mut router = Router::new()
        .route(
            "/hello/:name",
            get(|Path(name): Path<String>| async move { format!("Hello, {name}!") })
                // this will cache responses with each `:name` for 60 seconds.
                .layer(CacheLayer::with_lifespan(60)),
        );

    let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
    axum::serve(listener, router).await.unwrap();
}

For more see the documentation.

Dependencies

~6MB
~108K SLoC