Module add_extension
Expand description
Middleware that clones a value into the incoming input extensions
§Example
use std::{sync::Arc, convert::Infallible};
use rama_core::{extensions::{Extensions, ExtensionsRef}, Service, Layer, service::service_fn};
use rama_core::layer::add_extension::AddExtensionLayer;
use rama_core::error::BoxError;
// Shared state across all request handlers --- in this case, a pool of database connections.
struct State {
pool: DatabaseConnectionPool,
}
// Request can be any type that implements [`ExtensionsRef`]
async fn handle(req: Extensions) -> Result<(), Infallible>
{
// Grab the state from the request extensions.
let state = req.extensions().get::<Arc<State>>().unwrap();
Ok(())
}
// Construct the shared state.
let state = State {
pool: DatabaseConnectionPool::new(),
};
let mut service = (
// Share an `Arc<State>` with all requests.
AddExtensionLayer::new(Arc::new(state)),
).into_layer(service_fn(handle));
// Call the service.
let response = service
.serve(Extensions::new())
.await?;Note though that extensions are best not used for State that you expect to be there, but instead use extensions for optional behaviour to change. Static typed state is better embedded in service structs or as state for routers.
Structs§
- AddExtension
- Middleware for adding some shareable value to incoming Context.
- AddExtension
Layer Layerfor adding some shareable value to incoming Context.