HttpCacheOptions

Struct HttpCacheOptions 

Source
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()
};
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

Source

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

Source

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

Source§

fn clone(&self) -> HttpCacheOptions

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for HttpCacheOptions

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for HttpCacheOptions

Source§

fn default() -> HttpCacheOptions

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> ErasedDestructor for T
where T: 'static,