tower_http

Module add_extension

Source
Available on crate feature add-extension only.
Expand description

Middleware that clones a value into each request’s extensions.

§Example

use tower_http::add_extension::AddExtensionLayer;
use tower::{Service, ServiceExt, ServiceBuilder, service_fn};
use http::{Request, Response};
use bytes::Bytes;
use http_body_util::Full;
use std::{sync::Arc, convert::Infallible};

// Shared state across all request handlers --- in this case, a pool of database connections.
struct State {
    pool: DatabaseConnectionPool,
}

async fn handle(req: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, Infallible> {
    // Grab the state from the request extensions.
    let state = req.extensions().get::<Arc<State>>().unwrap();

    Ok(Response::new(Full::default()))
}

// Construct the shared state.
let state = State {
    pool: DatabaseConnectionPool::new(),
};

let mut service = ServiceBuilder::new()
    // Share an `Arc<State>` with all requests.
    .layer(AddExtensionLayer::new(Arc::new(state)))
    .service_fn(handle);

// Call the service.
let response = service
    .ready()
    .await?
    .call(Request::new(Full::default()))
    .await?;

Structs§