mod.rs
This file
Path
axum-extra/src/handler/mod.rs
199 lines · 6.2 KiB · Rust
Last changed by
chore: fix typos (#3758)David Pedersenbefore adoption5bc0046
History of this fileTake it
1//! Additional handler utilities.23use axum::body::Body;4use axum::extract::Request;5use axum::{6 extract::FromRequest,7 handler::Handler,8 response::{IntoResponse, Response},9};10use futures_core::future::BoxFuture;11use futures_util::future::{FutureExt, Map};12use std::{future::Future, marker::PhantomData};1314mod or;1516pub use self::or::Or;1718/// Trait for async functions that can be used to handle requests.19///20/// This trait is similar to [`Handler`] but rather than taking the request it takes the extracted21/// inputs.22///23/// The drawback of this trait is that you cannot apply middleware to individual handlers like you24/// can with [`Handler::layer`].25pub trait HandlerCallWithExtractors<T, S>: Sized {26 /// The type of future calling this handler returns.27 type Future: Future<Output = Response> + Send + 'static;2829 /// Call the handler with the extracted inputs.30 fn call(self, extractors: T, state: S) -> <Self as HandlerCallWithExtractors<T, S>>::Future;3132 /// Convert this `HandlerCallWithExtractors` into [`Handler`].33 fn into_handler(self) -> IntoHandler<Self, T, S> {34 IntoHandler {35 handler: self,36 _marker: PhantomData,37 }38 }3940 /// Chain two handlers together, running the second one if the first one rejects.41 ///42 /// Note that this only moves to the next handler if an extractor fails. The response from43 /// handlers are not considered.44 ///45 /// # Example46 ///47 /// ```48 /// use axum_extra::handler::HandlerCallWithExtractors;49 /// use axum::{50 /// Router,51 /// routing::get,52 /// extract::FromRequestParts,53 /// };54 ///55 /// // handlers for varying levels of access56 /// async fn admin(admin: AdminPermissions) {57 /// // request came from an admin58 /// }59 ///60 /// async fn user(user: User) {61 /// // we have a `User`62 /// }63 ///64 /// async fn guest() {65 /// // `AdminPermissions` and `User` failed, so we're just a guest66 /// }67 ///68 /// // extractors for checking permissions69 /// struct AdminPermissions {}70 ///71 /// impl<S> FromRequestParts<S> for AdminPermissions72 /// where73 /// S: Send + Sync,74 /// {75 /// // check for admin permissions...76 /// # type Rejection = ();77 /// # async fn from_request_parts(parts: &mut http::request::Parts, state: &S) -> Result<Self, Self::Rejection> {78 /// # todo!()79 /// # }80 /// }81 ///82 /// struct User {}83 ///84 /// impl<S> FromRequestParts<S> for User85 /// where86 /// S: Send + Sync,87 /// {88 /// // check for a logged in user...89 /// # type Rejection = ();90 /// # async fn from_request_parts(parts: &mut http::request::Parts, state: &S) -> Result<Self, Self::Rejection> {91 /// # todo!()92 /// # }93 /// }94 ///95 /// let app = Router::new().route(96 /// "/users/{id}",97 /// get(98 /// // first try `admin`, if that rejects run `user`, finally falling back99 /// // to `guest`100 /// admin.or(user).or(guest)101 /// )102 /// );103 /// # let _: Router = app;104 /// ```105 fn or<R, Rt>(self, rhs: R) -> Or<Self, R, T, Rt, S>106 where107 R: HandlerCallWithExtractors<Rt, S>,108 {109 Or {110 lhs: self,111 rhs,112 _marker: PhantomData,113 }114 }115}116117macro_rules! impl_handler_call_with {118 ( $($ty:ident),* $(,)? ) => {119 #[allow(non_snake_case)]120 impl<F, Fut, S, $($ty,)*> HandlerCallWithExtractors<($($ty,)*), S> for F121 where122 F: FnOnce($($ty,)*) -> Fut,123 Fut: Future + Send + 'static,124 Fut::Output: IntoResponse,125 {126 // this puts `futures_util` in our public API but that's fine in axum-extra127 type Future = Map<Fut, fn(Fut::Output) -> Response>;128129 fn call(130 self,131 ($($ty,)*): ($($ty,)*),132 _state: S,133 ) -> <Self as HandlerCallWithExtractors<($($ty,)*), S>>::Future {134 self($($ty,)*).map(IntoResponse::into_response)135 }136 }137 };138 }139140impl_handler_call_with!();141impl_handler_call_with!(T1);142impl_handler_call_with!(T1, T2);143impl_handler_call_with!(T1, T2, T3);144impl_handler_call_with!(T1, T2, T3, T4);145impl_handler_call_with!(T1, T2, T3, T4, T5);146impl_handler_call_with!(T1, T2, T3, T4, T5, T6);147impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7);148impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8);149impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9);150impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);151impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);152impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);153impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);154impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14);155impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15);156impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16);157158/// A [`Handler`] created from a [`HandlerCallWithExtractors`].159///160/// Created with [`HandlerCallWithExtractors::into_handler`].161#[allow(missing_debug_implementations)]162pub struct IntoHandler<H, T, S> {163 handler: H,164 _marker: PhantomData<fn() -> (T, S)>,165}166167impl<H, T, S> Handler<T, S> for IntoHandler<H, T, S>168where169 H: HandlerCallWithExtractors<T, S> + Clone + Send + Sync + 'static,170 T: FromRequest<S> + Send + 'static,171 T::Rejection: Send,172 S: Send + Sync + 'static,173{174 type Future = BoxFuture<'static, Response>;175176 fn call(self, req: Request, state: S) -> Self::Future {177 let req = req.map(Body::new);178 Box::pin(async move {179 match T::from_request(req, &state).await {180 Ok(t) => self.handler.call(t, state).await,181 Err(rejection) => rejection.into_response(),182 }183 })184 }185}186187impl<H, T, S> Copy for IntoHandler<H, T, S> where H: Copy {}188189impl<H, T, S> Clone for IntoHandler<H, T, S>190where191 H: Clone,192{193 fn clone(&self) -> Self {194 Self {195 handler: self.handler.clone(),196 _marker: self._marker,197 }198 }199}