pub struct HttpCacheOptions {
pub cache_options: Option<CacheOptions>,
pub cache_key: Option<Arc<dyn Fn(&Parts) -> String + Sync + Send>>,
pub cache_mode_fn: Option<Arc<dyn Fn(&Parts) -> CacheMode + Sync + Send>>,
pub response_cache_mode_fn: Option<Arc<dyn Fn(&Parts, &HttpResponse) -> Option<CacheMode> + Sync + Send>>,
pub cache_bust: Option<Arc<dyn Fn(&Parts, &Option<Arc<dyn Fn(&Parts) -> String + Sync + Send>>, &str) -> Vec<String> + Sync + Send>>,
pub cache_status_headers: bool,
pub max_ttl: Option<Duration>,
pub rate_limiter: Option<Arc<dyn CacheAwareRateLimiter>>,
}
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()
};
Fields§
§cache_options: Option<CacheOptions>
Override the default cache options.
cache_key: Option<Arc<dyn Fn(&Parts) -> String + Sync + Send>>
Override the default cache key generator.
cache_mode_fn: Option<Arc<dyn Fn(&Parts) -> CacheMode + Sync + Send>>
Override the default cache mode.
response_cache_mode_fn: Option<Arc<dyn Fn(&Parts, &HttpResponse) -> Option<CacheMode> + Sync + Send>>
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<Arc<dyn Fn(&Parts, &Option<Arc<dyn Fn(&Parts) -> String + Sync + Send>>, &str) -> Vec<String> + Sync + Send>>
Bust the caches of the returned keys.
cache_status_headers: bool
Determines 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.
rate_limiter: Option<Arc<dyn CacheAwareRateLimiter>>
Rate limiter that applies only on cache misses. When enabled, requests that result in cache hits are returned immediately, while cache misses are rate limited before making network requests. This provides the optimal behavior for web scrapers and similar applications.
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>, Box<dyn Error + Sync + Send>>
pub fn http_response_to_response<B>( http_response: &HttpResponse, body: B, ) -> Result<Response<B>, Box<dyn Error + Sync + Send>>
Converts HttpResponse to http::Response with the given body type
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
Source§impl Default for HttpCacheOptions
impl Default for HttpCacheOptions
Source§fn default() -> HttpCacheOptions
fn default() -> 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