Files
axum/src/handler/mod.rs
T

246 lines
7.2 KiB
Rust
Raw Normal View History

2021-06-07 16:28:40 +02:00
//! Async functions that can be used to handle requests.
2021-06-06 11:37:08 +02:00
use crate::{
2021-07-22 13:23:50 +02:00
body::{box_body, BoxBody},
extract::{FromRequest, RequestParts},
2021-06-06 11:37:08 +02:00
response::IntoResponse,
routing::{MethodNotAllowed, MethodRouter},
2021-08-21 15:01:30 +02:00
BoxError,
2021-06-06 11:37:08 +02:00
};
2021-05-30 13:24:03 +02:00
use async_trait::async_trait;
2021-06-01 17:17:10 +02:00
use bytes::Bytes;
2021-05-30 13:24:03 +02:00
use http::{Request, Response};
use std::{fmt, future::Future, marker::PhantomData};
2021-08-21 15:01:30 +02:00
use tower::ServiceExt;
use tower_layer::Layer;
use tower_service::Service;
2021-06-06 23:58:44 +02:00
pub mod future;
2021-08-19 21:16:44 +02:00
mod into_service;
pub use self::into_service::IntoService;
pub(crate) mod sealed {
2021-06-07 15:45:19 +02:00
#![allow(unreachable_pub, missing_docs, missing_debug_implementations)]
2021-06-06 11:37:08 +02:00
2021-05-30 13:24:03 +02:00
pub trait HiddentTrait {}
pub struct Hidden;
impl HiddentTrait for Hidden {}
}
2021-06-07 15:45:19 +02:00
/// 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](crate::handler) for more details.
2021-05-30 13:24:03 +02:00
#[async_trait]
pub trait Handler<B, T>: Clone + Send + Sized + 'static {
// This seals the trait. We cannot use the regular "sealed super trait"
// approach due to coherence.
2021-05-30 13:24:03 +02:00
#[doc(hidden)]
type Sealed: sealed::HiddentTrait;
/// Call the handler with the given request.
async fn call(self, req: Request<B>) -> Response<BoxBody>;
2021-05-30 13:24:03 +02:00
2021-06-07 15:45:19 +02:00
/// 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.
///
2021-10-13 12:21:22 +02:00
/// Note this differs from [`routing::Router::layer`](crate::routing::Router::layer)
/// which adds a middleware to a group of routes.
///
2021-06-07 15:45:19 +02:00
/// # Example
///
/// Adding the [`tower::limit::ConcurrencyLimit`] middleware to a handler
/// can be done like so:
2021-06-07 15:45:19 +02:00
///
/// ```rust
2021-08-18 00:04:15 +02:00
/// use axum::{
/// routing::get,
/// handler::Handler,
/// Router,
2021-08-18 00:04:15 +02:00
/// };
2021-06-07 15:45:19 +02:00
/// use tower::limit::{ConcurrencyLimitLayer, ConcurrencyLimit};
///
2021-06-09 09:03:09 +02:00
/// async fn handler() { /* ... */ }
2021-06-07 15:45:19 +02:00
///
/// let layered_handler = handler.layer(ConcurrencyLimitLayer::new(64));
/// let app = Router::new().route("/", get(layered_handler));
2021-06-19 12:50:33 +02:00
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
2021-06-19 12:50:33 +02:00
/// # };
2021-06-07 15:45:19 +02:00
/// ```
2021-08-15 23:01:26 +02:00
fn layer<L>(self, layer: L) -> Layered<L::Service, T>
2021-05-30 13:24:03 +02:00
where
L: Layer<MethodRouter<Self, B, T, MethodNotAllowed>>,
2021-05-30 13:24:03 +02:00
{
Layered::new(layer.layer(crate::routing::any(self)))
2021-05-30 13:24:03 +02:00
}
2021-08-19 21:16:44 +02:00
/// Convert the handler into a [`Service`].
///
/// This allows you to serve a single handler if you don't need any routing:
///
/// ```rust
/// 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();
///
/// # async {
/// Server::bind(&SocketAddr::from(([127, 0, 0, 1], 3000)))
/// .serve(Shared::new(service))
/// .await?;
/// # Ok::<_, hyper::Error>(())
/// # };
/// ```
fn into_service(self) -> IntoService<Self, B, T> {
2021-08-19 21:16:44 +02:00
IntoService::new(self)
}
2021-05-30 13:24:03 +02:00
}
#[async_trait]
impl<F, Fut, Res, B> Handler<B, ()> for F
2021-05-30 13:24:03 +02:00
where
2021-08-15 23:01:26 +02:00
F: FnOnce() -> Fut + Clone + Send + Sync + 'static,
2021-05-31 20:42:57 +02:00
Fut: Future<Output = Res> + Send,
2021-06-06 22:41:52 +02:00
Res: IntoResponse,
B: Send + 'static,
2021-05-30 13:24:03 +02:00
{
type Sealed = sealed::Hidden;
async fn call(self, _req: Request<B>) -> Response<BoxBody> {
2021-07-22 13:23:50 +02:00
self().await.into_response().map(box_body)
2021-05-30 13:24:03 +02:00
}
}
macro_rules! impl_handler {
( $($ty:ident),* $(,)? ) => {
2021-05-30 13:24:03 +02:00
#[async_trait]
#[allow(non_snake_case)]
impl<F, Fut, B, Res, $($ty,)*> Handler<B, ($($ty,)*)> for F
2021-05-30 13:24:03 +02:00
where
F: FnOnce($($ty,)*) -> Fut + Clone + Send + Sync + 'static,
2021-05-31 20:42:57 +02:00
Fut: Future<Output = Res> + Send,
B: Send + 'static,
2021-06-06 22:41:52 +02:00
Res: IntoResponse,
$( $ty: FromRequest<B> + Send,)*
2021-05-30 13:24:03 +02:00
{
type Sealed = sealed::Hidden;
async fn call(self, req: Request<B>) -> Response<BoxBody> {
let mut req = RequestParts::new(req);
$(
let $ty = match $ty::from_request(&mut req).await {
Ok(value) => value,
Err(rejection) => return rejection.into_response().map(box_body),
};
)*
let res = self($($ty,)*).await;
res.into_response().map(box_body)
2021-05-30 13:24:03 +02:00
}
}
};
}
impl_handler!(T1);
impl_handler!(T1, T2);
impl_handler!(T1, T2, T3);
impl_handler!(T1, T2, T3, T4);
impl_handler!(T1, T2, T3, T4, T5);
impl_handler!(T1, T2, T3, T4, T5, T6);
impl_handler!(T1, T2, T3, T4, T5, T6, T7);
impl_handler!(T1, T2, T3, T4, T5, T6, T7, T8);
impl_handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9);
impl_handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
impl_handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
impl_handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
impl_handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
impl_handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14);
impl_handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15);
2021-05-30 13:24:03 +02:00
impl_handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16);
2021-06-07 15:45:19 +02:00
/// A [`Service`] created from a [`Handler`] by applying a Tower middleware.
///
/// Created with [`Handler::layer`]. See that method for more details.
2021-05-30 13:24:03 +02:00
pub struct Layered<S, T> {
svc: S,
_input: PhantomData<fn() -> T>,
}
2021-06-07 15:45:19 +02:00
impl<S, T> fmt::Debug for Layered<S, T>
where
S: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Layered").field("svc", &self.svc).finish()
}
}
2021-05-30 13:24:03 +02:00
impl<S, T> Clone for Layered<S, T>
where
S: Clone,
{
fn clone(&self) -> Self {
Self::new(self.svc.clone())
}
}
#[async_trait]
impl<S, T, ReqBody, ResBody> Handler<ReqBody, T> for Layered<S, T>
2021-05-30 13:24:03 +02:00
where
S: Service<Request<ReqBody>, Response = Response<ResBody>> + Clone + Send + 'static,
2021-06-06 22:41:52 +02:00
S::Error: IntoResponse,
2021-05-30 13:24:03 +02:00
S::Future: Send,
2021-08-15 23:01:26 +02:00
T: 'static,
2021-06-19 12:50:33 +02:00
ReqBody: Send + 'static,
ResBody: http_body::Body<Data = Bytes> + Send + Sync + 'static,
ResBody::Error: Into<BoxError> + Send + Sync + 'static,
2021-05-30 13:24:03 +02:00
{
type Sealed = sealed::Hidden;
async fn call(self, req: Request<ReqBody>) -> Response<BoxBody> {
2021-05-31 22:54:21 +02:00
match self
.svc
2021-05-30 13:24:03 +02:00
.oneshot(req)
.await
2021-05-31 22:54:21 +02:00
.map_err(IntoResponse::into_response)
{
2021-07-22 13:23:50 +02:00
Ok(res) => res.map(box_body),
Err(res) => res.map(box_body),
2021-05-31 22:54:21 +02:00
}
2021-05-30 13:24:03 +02:00
}
}
impl<S, T> Layered<S, T> {
pub(crate) fn new(svc: S) -> Self {
Self {
svc,
_input: PhantomData,
}
}
}
#[test]
fn traits() {
use crate::tests::*;
assert_send::<MethodRouter<(), NotSendSync, NotSendSync, ()>>();
assert_sync::<MethodRouter<(), NotSendSync, NotSendSync, ()>>();
2021-06-06 15:19:54 +02:00
}