pub struct HttpCacheOptions {
pub cache_options: Option<CacheOptions>,
pub cache_key: Option<CacheKey>,
pub cache_mode_fn: Option<CacheModeFn>,
pub response_cache_mode_fn: Option<ResponseCacheModeFn>,
pub cache_bust: Option<CacheBust>,
pub modify_response: Option<ModifyResponse>,
pub cache_status_headers: bool,
pub max_ttl: Option<Duration>,
pub metadata_provider: Option<MetadataProvider>,
}Expand description
Configuration options for customizing HTTP cache behavior on a per-request basis.
This struct allows you to override default caching behavior for individual requests by providing custom cache options, cache keys, cache modes, and cache busting logic.
§Examples
§Basic Custom Cache Key
use http_cache::{HttpCacheOptions, CacheKey};
use http::request::Parts;
use std::sync::Arc;
let options = HttpCacheOptions {
cache_key: Some(Arc::new(|parts: &Parts| {
format!("custom:{}:{}", parts.method, parts.uri.path())
})),
..Default::default()
};§Custom Cache Mode per Request
use http_cache::{HttpCacheOptions, CacheMode, CacheModeFn};
use http::request::Parts;
use std::sync::Arc;
let options = HttpCacheOptions {
cache_mode_fn: Some(Arc::new(|parts: &Parts| {
if parts.headers.contains_key("x-no-cache") {
CacheMode::NoStore
} else {
CacheMode::Default
}
})),
..Default::default()
};§Response-Based Cache Mode Override
use http_cache::{HttpCacheOptions, ResponseCacheModeFn, CacheMode};
use http::request::Parts;
use http_cache::HttpResponse;
use std::sync::Arc;
let options = HttpCacheOptions {
response_cache_mode_fn: Some(Arc::new(|_parts: &Parts, response: &HttpResponse| {
// Force cache 2xx responses even if headers say not to cache
if response.status >= 200 && response.status < 300 {
Some(CacheMode::ForceCache)
} else if response.status == 429 { // Rate limited
Some(CacheMode::NoStore) // Don't cache rate limit responses
} else {
None // Use default behavior
}
})),
..Default::default()
};§Content-Type Based Cache Mode Override
use http_cache::{HttpCacheOptions, ResponseCacheModeFn, CacheMode};
use http::request::Parts;
use http_cache::HttpResponse;
use std::sync::Arc;
let options = HttpCacheOptions {
response_cache_mode_fn: Some(Arc::new(|_parts: &Parts, response: &HttpResponse| {
// Cache different content types with different strategies
if let Some(content_type) = response.headers.get("content-type") {
match content_type.as_str() {
ct if ct.starts_with("application/json") => Some(CacheMode::ForceCache),
ct if ct.starts_with("image/") => Some(CacheMode::Default),
ct if ct.starts_with("text/html") => Some(CacheMode::NoStore),
_ => None, // Use default behavior for other types
}
} else {
Some(CacheMode::NoStore) // No content-type = don't cache
}
})),
..Default::default()
};§Cache Busting for Related Resources
use http_cache::{HttpCacheOptions, CacheBust, CacheKey};
use http::request::Parts;
use std::sync::Arc;
let options = HttpCacheOptions {
cache_bust: Some(Arc::new(|parts: &Parts, _cache_key: &Option<CacheKey>, _uri: &str| {
if parts.method == "POST" && parts.uri.path().starts_with("/api/users") {
vec![
"GET:/api/users".to_string(),
"GET:/api/users/list".to_string(),
]
} else {
vec![]
}
})),
..Default::default()
};§Storing Metadata with Cached Responses
use http_cache::{HttpCacheOptions, MetadataProvider};
use http::{request, response};
use std::sync::Arc;
let options = HttpCacheOptions {
metadata_provider: Some(Arc::new(|request_parts: &request::Parts, response_parts: &response::Parts| {
// Store computed information with the cached response
let content_type = response_parts
.headers
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("unknown");
// Return serialized metadata (users handle serialization)
Some(format!("path={};content-type={}", request_parts.uri.path(), content_type).into_bytes())
})),
..Default::default()
};Fields§
§cache_options: Option<CacheOptions>Override the default cache options.
cache_key: Option<CacheKey>Override the default cache key generator.
cache_mode_fn: Option<CacheModeFn>Override the default cache mode.
response_cache_mode_fn: Option<ResponseCacheModeFn>Override cache behavior based on the response received.
This function is called after receiving a response and can override
the cache mode for that specific response. Returning None means
use the default cache mode. This allows fine-grained control over
caching behavior based on response status, headers, or content.
cache_bust: Option<CacheBust>Bust the caches of the returned keys.
modify_response: Option<ModifyResponse>Modifies the response before storing it in the cache.
cache_status_headers: boolDetermines if the cache status headers should be added to the response.
max_ttl: Option<Duration>Maximum time-to-live for cached responses.
When set, this overrides any longer cache durations specified by the server.
Particularly useful with CacheMode::IgnoreRules to provide expiration control.
metadata_provider: Option<MetadataProvider>Optional callback to provide metadata to store alongside cached responses. The callback receives request and response parts and can return metadata bytes. This is useful for storing computed information that should be associated with cached responses without recomputation on cache hits.
Implementations§
Source§impl HttpCacheOptions
impl HttpCacheOptions
Sourcepub fn create_cache_key_for_invalidation(
&self,
parts: &Parts,
method_override: &str,
) -> String
pub fn create_cache_key_for_invalidation( &self, parts: &Parts, method_override: &str, ) -> String
Helper function for other crates to generate cache keys for invalidation This ensures consistent cache key generation across all implementations
Sourcepub fn http_response_to_response<B>(
http_response: &HttpResponse,
body: B,
) -> Result<Response<B>>
pub fn http_response_to_response<B>( http_response: &HttpResponse, body: B, ) -> Result<Response<B>>
Converts HttpResponse to http::Response with the given body type
Sourcepub fn generate_metadata(
&self,
request_parts: &Parts,
response_parts: &Parts,
) -> Option<HttpCacheMetadata>
pub fn generate_metadata( &self, request_parts: &Parts, response_parts: &Parts, ) -> Option<HttpCacheMetadata>
Generates metadata for a response using the metadata_provider callback if configured
Trait Implementations§
Source§impl Clone for HttpCacheOptions
impl Clone for HttpCacheOptions
Source§fn clone(&self) -> HttpCacheOptions
fn clone(&self) -> HttpCacheOptions
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for HttpCacheOptions
impl Debug for HttpCacheOptions
Auto Trait Implementations§
impl Freeze for HttpCacheOptions
impl !RefUnwindSafe for HttpCacheOptions
impl Send for HttpCacheOptions
impl Sync for HttpCacheOptions
impl Unpin for HttpCacheOptions
impl !UnwindSafe for HttpCacheOptions
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more