Module tower_http::add_extension
source · [−]This is supported 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 hyper::Body;
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<Body>) -> Result<Response<Body>, Infallible> {
// Grab the state from the request extensions.
let state = req.extensions().get::<Arc<State>>().unwrap();
Ok(Response::new(Body::empty()))
}
// 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(Body::empty()))
.await?;
Structs
Middleware for adding some shareable value to request extensions.
Layer
for adding some shareable value to request extensions.