Trait axum::handler::Handler [−][src]
pub trait Handler<B, T>: Clone + Send + Sized + 'static {
fn call<'async_trait>(
self,
req: Request<B>
) -> Pin<Box<dyn Future<Output = Response<BoxBody>> + Send + 'async_trait>>
where
Self: 'async_trait;
fn layer<L>(self, layer: L) -> Layered<L::Service, T>
where
L: Layer<OnMethod<Self, B, T, EmptyRouter>>,
{ ... }
fn into_service(self) -> IntoService<Self, B, T> { ... }
}
Expand description
Trait for async functions that can be used to handle requests.
You shouldn’t need to depend on this trait directly. It is automatically implemented to closures of the right types.
See the module docs for more details.
Required methods
Provided methods
Apply a tower::Layer
to the handler.
All requests to the handler will be processed by the layer’s corresponding middleware.
This can be used to add additional processing to a request for a single handler.
Note this differs from routing::Layered
which adds a middleware to a group of routes.
Example
Adding the tower::limit::ConcurrencyLimit
middleware to a handler
can be done like so:
use axum::{
handler::{get, Handler},
Router,
};
use tower::limit::{ConcurrencyLimitLayer, ConcurrencyLimit};
async fn handler() { /* ... */ }
let layered_handler = handler.layer(ConcurrencyLimitLayer::new(64));
let app = Router::new().route("/", get(layered_handler));
When adding middleware that might fail its recommended to handle those
errors. See Layered::handle_error
for more details.
fn into_service(self) -> IntoService<Self, B, T>
fn into_service(self) -> IntoService<Self, B, T>
Convert the handler into a Service
.
This allows you to serve a single handler if you don’t need any routing:
use axum::{
Server, handler::Handler, http::{Uri, Method}, response::IntoResponse,
};
use tower::make::Shared;
use std::net::SocketAddr;
async fn handler(method: Method, uri: Uri, body: String) -> impl IntoResponse {
format!("received `{} {}` with body `{:?}`", method, uri, body)
}
let service = handler.into_service();
Server::bind(&SocketAddr::from(([127, 0, 0, 1], 3000)))
.serve(Shared::new(service))
.await?;