Caching Headers

A middleware that provides support for configuring caching headers.

Cache control is a crucial part of web performance optimization. By correctly setting caching headers, unnecessary network requests can be reduced, thereby improving application performance. Cache-Control is an HTTP response header used to specify browser caching policies. It controls who can cache responses, under what conditions, and for how long.

Internally, it includes implementations of three Handlers: CachingHeaders, Modified, and ETag. CachingHeaders is a combination of the latter two. Under normal circumstances, CachingHeaders is used.

  • Modified: Provides cache validation based on the resource's last modified time.
  • ETag: Uses Entity Tags to offer a more precise resource validation mechanism.
  • CachingHeaders: Combines the above two mechanisms to provide comprehensive cache control support.

Example Code

main.rs
Cargo.toml
use salvo::prelude::*;

// Handler that returns a simple "Hello World" response
#[handler]
async fn hello() -> &'static str {
    "Hello World"
}

#[tokio::main]
async fn main() {
    // Initialize logging system
    tracing_subscriber::fmt().init();

    // Set up router with caching headers and compression middleware
    // CachingHeader must be before Compression to properly set cache control headers
    let router = Router::with_hoop(CachingHeaders::new())
        .hoop(Compression::new().min_length(0)) // Enable compression for all responses
        .get(hello);

    // Bind server to port 8698 and start serving
    let acceptor = TcpListener::new("0.0.0.0:8698").bind().await;
    Server::new(acceptor).serve(router).await;
}