Files
axum/src/handler/future.rs
T

76 lines
1.9 KiB
Rust
Raw Normal View History

//! Handler future types.
2021-08-15 20:27:13 +02:00
use crate::body::{box_body, BoxBody};
use crate::util::{Either, EitherProj};
use futures_util::{
future::{BoxFuture, Map},
ready,
};
2021-08-15 20:27:13 +02:00
use http::{Method, Request, Response};
use http_body::Empty;
use pin_project_lite::pin_project;
use std::{
2021-08-19 21:16:44 +02:00
convert::Infallible,
2021-08-15 23:01:26 +02:00
fmt,
future::Future,
pin::Pin,
task::{Context, Poll},
};
2021-08-21 15:01:30 +02:00
use tower::util::Oneshot;
use tower_service::Service;
pin_project! {
/// The response future for [`OnMethod`](super::OnMethod).
2021-08-15 23:01:26 +02:00
pub struct OnMethodFuture<F, B>
where
F: Service<Request<B>>
{
#[pin]
2021-08-15 23:01:26 +02:00
pub(super) inner: Either<
BoxFuture<'static, Response<BoxBody>>,
2021-08-15 23:01:26 +02:00
Oneshot<F, Request<B>>,
>,
2021-08-15 20:27:13 +02:00
pub(super) req_method: Method,
}
}
2021-08-15 23:01:26 +02:00
impl<F, B> Future for OnMethodFuture<F, B>
where
2021-08-15 23:01:26 +02:00
F: Service<Request<B>, Response = Response<BoxBody>>,
{
2021-08-15 23:01:26 +02:00
type Output = Result<Response<BoxBody>, F::Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2021-08-15 20:27:13 +02:00
let this = self.project();
let response = match this.inner.project() {
EitherProj::A { inner } => ready!(inner.poll(cx)),
EitherProj::B { inner } => ready!(inner.poll(cx))?,
};
2021-08-15 20:27:13 +02:00
if this.req_method == &Method::HEAD {
let response = response.map(|_| box_body(Empty::new()));
Poll::Ready(Ok(response))
} else {
Poll::Ready(Ok(response))
}
}
}
2021-08-15 23:01:26 +02:00
impl<F, B> fmt::Debug for OnMethodFuture<F, B>
where
F: Service<Request<B>>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OnMethodFuture").finish()
}
}
2021-08-19 21:16:44 +02:00
opaque_future! {
/// The response future for [`IntoService`](super::IntoService).
pub type IntoServiceFuture =
Map<
BoxFuture<'static, Response<BoxBody>>,
fn(Response<BoxBody>) -> Result<Response<BoxBody>, Infallible>,
>;
2021-08-19 21:16:44 +02:00
}