Cache Headers

Middleware providing support for cache header configuration.

Cache control is an essential part of web performance optimization. By correctly setting cache headers, you can reduce unnecessary network requests and improve application performance. Cache-Control is an HTTP response header directive used to specify browser caching policies, controlling who can cache responses under what conditions and for how long.

The implementation actually includes three Handler implementations: CachingHeaders, Modified, and ETag. CachingHeaders is a combination of the latter two. Under normal circumstances, you should use CachingHeaders.

  • Modified: Provides cache validation based on the resource's last modification time
  • ETag: Uses Entity Tags to provide more precise resource validation mechanisms
  • CachingHeaders: Combines both mechanisms above to provide comprehensive cache control support

Example Code

main.rs
Cargo.toml
caching-headers/src/main.rs
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 5800 and start serving
let acceptor = TcpListener::new("0.0.0.0:5800").bind().await;
Server::new(acceptor).serve(router).await;
}