Files
axum/src/handler/mod.rs
T

635 lines
17 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},
2021-06-06 11:37:08 +02:00
extract::FromRequest,
response::IntoResponse,
2021-06-12 23:59:18 +02:00
routing::{EmptyRouter, MethodFilter, RouteFuture},
2021-06-06 15:19:54 +02:00
service::HandleError,
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::{
2021-05-31 22:54:21 +02:00
convert::Infallible,
2021-06-07 15:45:19 +02:00
fmt,
2021-05-30 13:24:03 +02:00
future::Future,
marker::PhantomData,
task::{Context, Poll},
};
2021-06-06 23:58:44 +02:00
use tower::{BoxError, Layer, Service, ServiceExt};
pub mod future;
2021-06-07 15:45:19 +02:00
/// Route requests to the given handler regardless of the HTTP method of the
/// request.
///
/// # Example
///
/// ```rust
2021-07-09 21:36:14 +02:00
/// use axum::prelude::*;
2021-06-07 15:45:19 +02:00
///
2021-06-09 09:03:09 +02:00
/// async fn handler() {}
2021-06-07 15:45:19 +02:00
///
/// // All requests to `/` will go to `handler` regardless of the HTTP method.
/// let app = route("/", any(handler));
2021-06-19 12:50:33 +02:00
/// # async {
/// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
2021-06-07 15:45:19 +02:00
/// ```
2021-06-19 12:50:33 +02:00
pub fn any<H, B, T>(handler: H) -> OnMethod<IntoService<H, B, T>, EmptyRouter>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
on(MethodFilter::Any, handler)
}
2021-06-07 15:45:19 +02:00
/// Route `CONNECT` requests to the given handler.
///
/// See [`get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn connect<H, B, T>(handler: H) -> OnMethod<IntoService<H, B, T>, EmptyRouter>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
on(MethodFilter::Connect, handler)
}
2021-06-07 15:45:19 +02:00
/// Route `DELETE` requests to the given handler.
///
/// See [`get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn delete<H, B, T>(handler: H) -> OnMethod<IntoService<H, B, T>, EmptyRouter>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
on(MethodFilter::Delete, handler)
}
2021-06-06 11:37:08 +02:00
2021-06-07 15:45:19 +02:00
/// Route `GET` requests to the given handler.
///
/// # Example
///
/// ```rust
2021-07-09 21:36:14 +02:00
/// use axum::prelude::*;
2021-06-07 15:45:19 +02:00
///
2021-06-09 09:03:09 +02:00
/// async fn handler() {}
2021-06-07 15:45:19 +02:00
///
/// // Requests to `GET /` will go to `handler`.
/// let app = route("/", get(handler));
2021-06-19 12:50:33 +02:00
/// # async {
/// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
2021-06-07 15:45:19 +02:00
/// ```
2021-06-19 12:50:33 +02:00
pub fn get<H, B, T>(handler: H) -> OnMethod<IntoService<H, B, T>, EmptyRouter>
2021-06-06 11:37:08 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 11:37:08 +02:00
{
on(MethodFilter::Get, handler)
}
2021-06-07 15:45:19 +02:00
/// Route `HEAD` requests to the given handler.
///
/// See [`get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn head<H, B, T>(handler: H) -> OnMethod<IntoService<H, B, T>, EmptyRouter>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
on(MethodFilter::Head, handler)
}
2021-06-07 15:45:19 +02:00
/// Route `OPTIONS` requests to the given handler.
///
/// See [`get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn options<H, B, T>(handler: H) -> OnMethod<IntoService<H, B, T>, EmptyRouter>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
on(MethodFilter::Options, handler)
}
2021-06-07 15:45:19 +02:00
/// Route `PATCH` requests to the given handler.
///
/// See [`get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn patch<H, B, T>(handler: H) -> OnMethod<IntoService<H, B, T>, EmptyRouter>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
on(MethodFilter::Patch, handler)
}
2021-06-07 15:45:19 +02:00
/// Route `POST` requests to the given handler.
///
/// See [`get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn post<H, B, T>(handler: H) -> OnMethod<IntoService<H, B, T>, EmptyRouter>
2021-06-06 11:37:08 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 11:37:08 +02:00
{
on(MethodFilter::Post, handler)
}
2021-06-07 15:45:19 +02:00
/// Route `PUT` requests to the given handler.
///
/// See [`get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn put<H, B, T>(handler: H) -> OnMethod<IntoService<H, B, T>, EmptyRouter>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
on(MethodFilter::Put, handler)
}
2021-06-07 15:45:19 +02:00
/// Route `TRACE` requests to the given handler.
///
/// See [`get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn trace<H, B, T>(handler: H) -> OnMethod<IntoService<H, B, T>, EmptyRouter>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
on(MethodFilter::Trace, handler)
}
2021-06-07 15:45:19 +02:00
/// Route requests with the given method to the handler.
///
/// # Example
///
/// ```rust
2021-07-09 21:36:14 +02:00
/// use axum::{handler::on, routing::MethodFilter, prelude::*};
2021-06-07 15:45:19 +02:00
///
2021-06-09 09:03:09 +02:00
/// async fn handler() {}
2021-06-07 15:45:19 +02:00
///
/// // Requests to `POST /` will go to `handler`.
/// let app = route("/", on(MethodFilter::Post, handler));
2021-06-19 12:50:33 +02:00
/// # async {
/// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
2021-06-07 15:45:19 +02:00
/// ```
2021-06-19 12:50:33 +02:00
pub fn on<H, B, T>(method: MethodFilter, handler: H) -> OnMethod<IntoService<H, B, T>, EmptyRouter>
2021-06-06 11:37:08 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 11:37:08 +02:00
{
2021-06-06 15:19:54 +02:00
OnMethod {
method,
svc: handler.into_service(),
fallback: EmptyRouter::method_not_allowed(),
2021-06-06 15:19:54 +02:00
}
2021-06-06 11:37:08 +02:00
}
2021-05-30 13:24:03 +02:00
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]
2021-06-19 12:50:33 +02:00
pub trait Handler<B, In>: Sized {
// 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;
2021-06-07 15:45:19 +02:00
/// Call the handler with the given request.
2021-06-19 12:50:33 +02:00
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.
///
/// Note this differes from [`routing::Layered`](crate::routing::Layered)
/// 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-07-09 21:36:14 +02:00
/// use axum::prelude::*;
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));
2021-06-19 12:50:33 +02:00
/// let app = route("/", get(layered_handler));
/// # async {
/// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
2021-06-07 15:45:19 +02:00
/// ```
///
2021-07-05 16:18:39 +02:00
/// When adding middleware that might fail its recommended to handle those
2021-06-07 15:45:19 +02:00
/// errors. See [`Layered::handle_error`] for more details.
2021-05-30 13:24:03 +02:00
fn layer<L>(self, layer: L) -> Layered<L::Service, In>
where
2021-06-19 12:50:33 +02:00
L: Layer<IntoService<Self, B, In>>,
2021-05-30 13:24:03 +02:00
{
2021-06-06 11:37:08 +02:00
Layered::new(layer.layer(IntoService::new(self)))
}
2021-06-07 15:45:19 +02:00
/// Convert the handler into a [`Service`].
2021-06-19 12:50:33 +02:00
fn into_service(self) -> IntoService<Self, B, In> {
2021-06-06 11:37:08 +02:00
IntoService::new(self)
2021-05-30 13:24:03 +02:00
}
}
#[async_trait]
2021-06-19 12:50:33 +02:00
impl<F, Fut, Res, B> Handler<B, ()> for F
2021-05-30 13:24:03 +02:00
where
2021-06-09 09:03:09 +02:00
F: FnOnce() -> Fut + Send + Sync,
2021-05-31 20:42:57 +02:00
Fut: Future<Output = Res> + Send,
2021-06-06 22:41:52 +02:00
Res: IntoResponse,
2021-06-19 12:50:33 +02:00
B: Send + 'static,
2021-05-30 13:24:03 +02:00
{
type Sealed = sealed::Hidden;
2021-06-19 12:50:33 +02:00
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 {
() => {
};
2021-05-30 13:24:03 +02:00
( $head:ident, $($tail:ident),* $(,)? ) => {
#[async_trait]
#[allow(non_snake_case)]
2021-06-19 12:50:33 +02:00
impl<F, Fut, B, Res, $head, $($tail,)*> Handler<B, ($head, $($tail,)*)> for F
2021-05-30 13:24:03 +02:00
where
2021-06-09 09:03:09 +02:00
F: FnOnce($head, $($tail,)*) -> Fut + Send + Sync,
2021-05-31 20:42:57 +02:00
Fut: Future<Output = Res> + Send,
2021-06-19 12:50:33 +02:00
B: Send + 'static,
2021-06-06 22:41:52 +02:00
Res: IntoResponse,
2021-06-19 12:50:33 +02:00
$head: FromRequest<B> + Send,
$( $tail: FromRequest<B> + Send, )*
2021-05-30 13:24:03 +02:00
{
type Sealed = sealed::Hidden;
2021-07-22 13:23:50 +02:00
async fn call(self, req: Request<B>) -> Response<BoxBody> {
let mut req = crate::extract::RequestParts::new(req);
2021-05-31 22:54:21 +02:00
let $head = match $head::from_request(&mut req).await {
Ok(value) => value,
2021-07-22 13:23:50 +02:00
Err(rejection) => return rejection.into_response().map(crate::body::box_body),
2021-05-31 22:54:21 +02:00
};
2021-05-30 13:24:03 +02:00
$(
2021-05-31 22:54:21 +02:00
let $tail = match $tail::from_request(&mut req).await {
Ok(value) => value,
2021-07-22 13:23:50 +02:00
Err(rejection) => return rejection.into_response().map(crate::body::box_body),
2021-05-31 22:54:21 +02:00
};
2021-05-30 13:24:03 +02:00
)*
2021-05-31 22:54:21 +02:00
2021-06-09 09:03:09 +02:00
let res = self($head, $($tail,)*).await;
2021-05-31 22:54:21 +02:00
2021-07-22 13:23:50 +02:00
res.into_response().map(crate::body::box_body)
2021-05-30 13:24:03 +02:00
}
}
impl_handler!($($tail,)*);
};
}
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]
2021-06-19 12:50:33 +02:00
impl<S, T, ReqBody, ResBody> Handler<ReqBody, T> for Layered<S, T>
2021-05-30 13:24:03 +02:00
where
2021-06-19 12:50:33 +02:00
S: Service<Request<ReqBody>, Response = Response<ResBody>> + Send,
2021-06-06 22:41:52 +02:00
S::Error: IntoResponse,
2021-05-30 13:24:03 +02:00
S::Future: Send,
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;
2021-06-19 12:50:33 +02:00
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,
}
}
2021-06-01 17:17:10 +02:00
2021-06-07 15:45:19 +02:00
/// Create a new [`Layered`] handler where errors will be handled using the
/// given closure.
///
2021-07-05 16:18:39 +02:00
/// This is used to convert errors to responses rather than simply
/// terminating the connection.
2021-06-07 15:45:19 +02:00
///
2021-07-22 15:00:33 +02:00
/// It works similarly to [`routing::Layered::handle_error`]. See that for more details.
2021-06-07 15:45:19 +02:00
///
2021-07-22 15:00:33 +02:00
/// [`routing::Layered::handle_error`]: crate::routing::Layered::handle_error
pub fn handle_error<F, ReqBody, ResBody, Res, E>(
2021-06-19 12:50:33 +02:00
self,
f: F,
) -> Layered<HandleError<S, F, ReqBody>, T>
2021-06-01 17:17:10 +02:00
where
2021-06-19 12:50:33 +02:00
S: Service<Request<ReqBody>, Response = Response<ResBody>>,
2021-07-22 15:00:33 +02:00
F: FnOnce(S::Error) -> Result<Res, E>,
2021-06-06 22:41:52 +02:00
Res: IntoResponse,
2021-06-01 17:17:10 +02:00
{
let svc = HandleError::new(self.svc, f);
Layered::new(svc)
}
2021-05-30 13:24:03 +02:00
}
2021-06-07 15:45:19 +02:00
/// An adapter that makes a [`Handler`] into a [`Service`].
///
/// Created with [`Handler::into_service`].
2021-06-19 12:50:33 +02:00
pub struct IntoService<H, B, T> {
2021-05-30 13:24:03 +02:00
handler: H,
2021-06-19 12:50:33 +02:00
_marker: PhantomData<fn() -> (B, T)>,
2021-05-30 13:24:03 +02:00
}
2021-06-19 12:50:33 +02:00
impl<H, B, T> IntoService<H, B, T> {
2021-06-06 11:37:08 +02:00
fn new(handler: H) -> Self {
2021-05-30 13:24:03 +02:00
Self {
handler,
2021-06-06 11:37:08 +02:00
_marker: PhantomData,
2021-05-30 13:24:03 +02:00
}
}
}
2021-06-19 12:50:33 +02:00
impl<H, B, T> fmt::Debug for IntoService<H, B, T>
2021-06-07 15:45:19 +02:00
where
H: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("IntoService")
.field("handler", &self.handler)
.finish()
}
}
2021-06-19 12:50:33 +02:00
impl<H, B, T> Clone for IntoService<H, B, T>
2021-05-30 13:24:03 +02:00
where
H: Clone,
{
fn clone(&self) -> Self {
Self {
handler: self.handler.clone(),
2021-06-06 11:37:08 +02:00
_marker: PhantomData,
2021-05-30 13:24:03 +02:00
}
}
}
2021-06-19 12:50:33 +02:00
impl<H, T, B> Service<Request<B>> for IntoService<H, B, T>
2021-05-30 13:24:03 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T> + Clone + Send + 'static,
B: Send + 'static,
2021-05-30 13:24:03 +02:00
{
2021-06-06 22:41:52 +02:00
type Response = Response<BoxBody>;
2021-05-31 22:54:21 +02:00
type Error = Infallible;
type Future = future::IntoServiceFuture;
2021-05-30 13:24:03 +02:00
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
2021-06-06 11:37:08 +02:00
// `IntoService` can only be constructed from async functions which are always ready, or from
2021-05-30 13:24:03 +02:00
// `Layered` which bufferes in `<Layered as Handler>::call` and is therefore also always
// ready.
Poll::Ready(Ok(()))
}
2021-06-19 12:50:33 +02:00
fn call(&mut self, req: Request<B>) -> Self::Future {
2021-05-30 13:24:03 +02:00
let handler = self.handler.clone();
2021-06-06 23:58:44 +02:00
let future = Box::pin(async move {
2021-06-06 22:41:52 +02:00
let res = Handler::call(handler, req).await;
Ok(res)
2021-06-06 23:58:44 +02:00
});
future::IntoServiceFuture { future }
2021-05-30 13:24:03 +02:00
}
}
2021-06-06 15:19:54 +02:00
/// A handler [`Service`] that accepts requests based on a [`MethodFilter`] and
/// allows chaining additional handlers.
2021-06-07 15:45:19 +02:00
#[derive(Debug, Clone, Copy)]
2021-06-06 15:19:54 +02:00
pub struct OnMethod<S, F> {
pub(crate) method: MethodFilter,
pub(crate) svc: S,
pub(crate) fallback: F,
}
impl<S, F> OnMethod<S, F> {
2021-06-07 15:45:19 +02:00
/// Chain an additional handler that will accept all requests regardless of
/// its HTTP method.
///
/// See [`OnMethod::get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn any<H, B, T>(self, handler: H) -> OnMethod<IntoService<H, B, T>, Self>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
self.on(MethodFilter::Any, handler)
}
2021-06-07 15:45:19 +02:00
/// Chain an additional handler that will only accept `CONNECT` requests.
///
/// See [`OnMethod::get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn connect<H, B, T>(self, handler: H) -> OnMethod<IntoService<H, B, T>, Self>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
self.on(MethodFilter::Connect, handler)
}
2021-06-07 15:45:19 +02:00
/// Chain an additional handler that will only accept `DELETE` requests.
///
/// See [`OnMethod::get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn delete<H, B, T>(self, handler: H) -> OnMethod<IntoService<H, B, T>, Self>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
self.on(MethodFilter::Delete, handler)
}
2021-06-07 15:45:19 +02:00
/// Chain an additional handler that will only accept `GET` requests.
///
/// # Example
///
/// ```rust
2021-07-09 21:36:14 +02:00
/// use axum::prelude::*;
2021-06-07 15:45:19 +02:00
///
2021-06-09 09:03:09 +02:00
/// async fn handler() {}
2021-06-07 15:45:19 +02:00
///
2021-06-09 09:03:09 +02:00
/// async fn other_handler() {}
2021-06-07 15:45:19 +02:00
///
/// // Requests to `GET /` will go to `handler` and `POST /` will go to
/// // `other_handler`.
/// let app = route("/", post(handler).get(other_handler));
2021-06-19 12:50:33 +02:00
/// # async {
/// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
2021-06-07 15:45:19 +02:00
/// ```
2021-06-19 12:50:33 +02:00
pub fn get<H, B, T>(self, handler: H) -> OnMethod<IntoService<H, B, T>, Self>
2021-06-06 15:19:54 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 15:19:54 +02:00
{
self.on(MethodFilter::Get, handler)
}
2021-06-07 15:45:19 +02:00
/// Chain an additional handler that will only accept `HEAD` requests.
///
/// See [`OnMethod::get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn head<H, B, T>(self, handler: H) -> OnMethod<IntoService<H, B, T>, Self>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
self.on(MethodFilter::Head, handler)
}
2021-06-07 15:45:19 +02:00
/// Chain an additional handler that will only accept `OPTIONS` requests.
///
/// See [`OnMethod::get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn options<H, B, T>(self, handler: H) -> OnMethod<IntoService<H, B, T>, Self>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
self.on(MethodFilter::Options, handler)
}
2021-06-07 15:45:19 +02:00
/// Chain an additional handler that will only accept `PATCH` requests.
///
/// See [`OnMethod::get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn patch<H, B, T>(self, handler: H) -> OnMethod<IntoService<H, B, T>, Self>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
self.on(MethodFilter::Patch, handler)
}
2021-06-07 15:45:19 +02:00
/// Chain an additional handler that will only accept `POST` requests.
///
/// See [`OnMethod::get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn post<H, B, T>(self, handler: H) -> OnMethod<IntoService<H, B, T>, Self>
2021-06-06 15:19:54 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 15:19:54 +02:00
{
self.on(MethodFilter::Post, handler)
}
2021-06-07 15:45:19 +02:00
/// Chain an additional handler that will only accept `PUT` requests.
///
/// See [`OnMethod::get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn put<H, B, T>(self, handler: H) -> OnMethod<IntoService<H, B, T>, Self>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
self.on(MethodFilter::Put, handler)
}
2021-06-07 15:45:19 +02:00
/// Chain an additional handler that will only accept `TRACE` requests.
///
/// See [`OnMethod::get`] for an example.
2021-06-19 12:50:33 +02:00
pub fn trace<H, B, T>(self, handler: H) -> OnMethod<IntoService<H, B, T>, Self>
2021-06-06 23:58:44 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 23:58:44 +02:00
{
self.on(MethodFilter::Trace, handler)
}
2021-06-07 15:45:19 +02:00
/// Chain an additional handler that will accept requests matching the given
/// `MethodFilter`.
///
/// # Example
///
/// ```rust
2021-07-09 21:36:14 +02:00
/// use axum::{routing::MethodFilter, prelude::*};
2021-06-07 15:45:19 +02:00
///
2021-06-09 09:03:09 +02:00
/// async fn handler() {}
2021-06-07 15:45:19 +02:00
///
2021-06-09 09:03:09 +02:00
/// async fn other_handler() {}
2021-06-07 15:45:19 +02:00
///
/// // Requests to `GET /` will go to `handler` and `DELETE /` will go to
/// // `other_handler`
/// let app = route("/", get(handler).on(MethodFilter::Delete, other_handler));
2021-06-19 12:50:33 +02:00
/// # async {
/// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
2021-06-07 15:45:19 +02:00
/// ```
2021-06-19 12:50:33 +02:00
pub fn on<H, B, T>(
self,
method: MethodFilter,
handler: H,
) -> OnMethod<IntoService<H, B, T>, Self>
2021-06-06 15:19:54 +02:00
where
2021-06-19 12:50:33 +02:00
H: Handler<B, T>,
2021-06-06 15:19:54 +02:00
{
OnMethod {
method,
svc: handler.into_service(),
fallback: self,
}
}
}
2021-06-19 12:50:33 +02:00
impl<S, F, B> Service<Request<B>> for OnMethod<S, F>
2021-06-06 15:19:54 +02:00
where
2021-06-19 12:50:33 +02:00
S: Service<Request<B>, Response = Response<BoxBody>, Error = Infallible> + Clone,
F: Service<Request<B>, Response = Response<BoxBody>, Error = Infallible> + Clone,
2021-06-06 15:19:54 +02:00
{
2021-06-13 10:10:37 +02:00
type Response = Response<BoxBody>;
2021-06-06 15:19:54 +02:00
type Error = Infallible;
2021-06-19 12:50:33 +02:00
type Future = RouteFuture<S, F, B>;
2021-06-06 15:19:54 +02:00
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
2021-06-19 12:50:33 +02:00
fn call(&mut self, req: Request<B>) -> Self::Future {
2021-06-12 23:59:18 +02:00
if self.method.matches(req.method()) {
let fut = self.svc.clone().oneshot(req);
RouteFuture::a(fut)
2021-06-06 15:19:54 +02:00
} else {
2021-06-12 23:59:18 +02:00
let fut = self.fallback.clone().oneshot(req);
RouteFuture::b(fut)
}
2021-06-06 15:19:54 +02:00
}
}