Crate http_cache_surf

Crate http_cache_surf 

Source
Expand description

HTTP caching middleware for the surf HTTP client.

This crate provides middleware for the surf HTTP client that implements HTTP caching according to RFC 7234. It supports various cache modes and storage backends.

§Basic Usage

Add HTTP caching to your surf client:

use surf::Client;
use http_cache_surf::{Cache, CACacheManager, HttpCache, CacheMode};
use macro_rules_attribute::apply;
use smol_macros::main;

#[apply(main!)]
async fn main() -> surf::Result<()> {
    let client = surf::Client::new()
        .with(Cache(HttpCache {
            mode: CacheMode::Default,
            manager: CACacheManager::new("./cache".into(), true),
            options: Default::default(),
        }));

    // This request will be cached according to response headers
    let mut res = client.get("https://httpbin.org/cache/60").await?;
    println!("Response: {}", res.body_string().await?);
     
    // Subsequent identical requests may be served from cache
    let mut cached_res = client.get("https://httpbin.org/cache/60").await?;
    println!("Cached response: {}", cached_res.body_string().await?);
     
    Ok(())
}

§Cache Modes

Control caching behavior with different modes:

use surf::Client;
use http_cache_surf::{Cache, CACacheManager, HttpCache, CacheMode};
use macro_rules_attribute::apply;
use smol_macros::main;

#[apply(main!)]
async fn main() -> surf::Result<()> {
    let client = surf::Client::new()
        .with(Cache(HttpCache {
            mode: CacheMode::ForceCache, // Cache everything, ignore headers
            manager: CACacheManager::new("./cache".into(), true),
            options: Default::default(),
        }));

    // This will be cached even if headers say not to cache
    let mut res = client.get("https://httpbin.org/uuid").await?;
    println!("{}", res.body_string().await?);
    Ok(())
}

§In-Memory Caching

Use the Moka in-memory cache:

use surf::Client;
use http_cache_surf::{Cache, MokaManager, HttpCache, CacheMode};
use http_cache_surf::MokaCache;
use macro_rules_attribute::apply;
use smol_macros::main;

#[apply(main!)]
async fn main() -> surf::Result<()> {
    let client = surf::Client::new()
        .with(Cache(HttpCache {
            mode: CacheMode::Default,
            manager: MokaManager::new(MokaCache::new(1000)), // Max 1000 entries
            options: Default::default(),
        }));

    let mut res = client.get("https://httpbin.org/cache/60").await?;
    println!("{}", res.body_string().await?);
    Ok(())
}

§Custom Cache Keys

Customize how cache keys are generated:

use surf::Client;
use http_cache_surf::{Cache, CACacheManager, HttpCache, CacheMode};
use http_cache::HttpCacheOptions;
use std::sync::Arc;
use macro_rules_attribute::apply;
use smol_macros::main;

#[apply(main!)]
async fn main() -> surf::Result<()> {
    let options = HttpCacheOptions {
        cache_key: Some(Arc::new(|parts: &http::request::Parts| {
            // Include query parameters in cache key
            format!("{}:{}", parts.method, parts.uri)
        })),
        ..Default::default()
    };
     
    let client = surf::Client::new()
        .with(Cache(HttpCache {
            mode: CacheMode::Default,
            manager: CACacheManager::new("./cache".into(), true),
            options,
        }));

    let mut res = client.get("https://httpbin.org/cache/60?param=value").await?;
    println!("{}", res.body_string().await?);
    Ok(())
}

Structs§

BadRequest
Error type for request parsing failure
CACacheManagermanager-cacache
Implements CacheManager with cacache as the backend.
Cache
A wrapper around HttpCache that implements surf::middleware::Middleware
DirectRateLimiterrate-limiting
A direct (non-keyed) rate limiter for simple use cases where all requests share the same limit
DomainRateLimiterrate-limiting
A domain-based rate limiter using governor that limits requests per domain
HttpCache
Caches requests according to http spec.
HttpCacheOptions
Configuration options for customizing HTTP cache behavior on a per-request basis.
MokaCachemanager-moka
A thread-safe, futures-aware concurrent in-memory cache.
MokaCacheBuildermanager-moka
Builds a Cache with various configuration knobs.
MokaManagermanager-moka
Implements CacheManager with moka as the backend.
Quotarate-limiting
A rate-limiting quota.

Enums§

CacheMode
Cache mode determines how the HTTP cache behaves for requests.
HttpCacheError
Unified error type for HTTP cache operations that works across all client libraries.
HttpHeaders
Represents HTTP headers in either legacy or modern format

Traits§

CacheAwareRateLimiterrate-limiting
A trait for rate limiting that can be implemented by different rate limiting strategies

Type Aliases§

ResponseCacheModeFn
A closure that takes http::request::Parts, HttpResponse and returns a CacheMode to override caching behavior based on the response