1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
//! Handler module for handle [`Request`].
//!
//! Middleware is actually also a `Handler`. They can do some processing before or after the request reaches the `Handler` that officially handles the request, such as: login verification, data compression, etc.
//!
//! Middleware is added through the `hoop` function of `Router`. The added middleware will affect the current `Router` and all its internal descendants `Router`.
//!
//! ## Macro `#[handler]`
//!
//! `#[handler]` can greatly simplify the writing of the code, and improve the flexibility of the code.
//!
//! It can be added to a function to make it implement `Handler`:
//!
//! ```
//! use salvo_core::prelude::*;
//!
//! #[handler]
//! async fn hello() -> &'static str {
//! "hello world!"
//! }
//! ````
//!
//! This is equivalent to:
//!
//! ```
//! use salvo_core::prelude::*;
//!
//! #[allow(non_camel_case_types)]
//! struct hello;
//!
//! #[async_trait]
//! impl Handler for hello {
//! async fn handle(&self, _req: &mut Request, _depot: &mut Depot, res: &mut Response, _ctrl: &mut FlowCtrl) {
//! res.render(Text::Plain("hello world!"));
//! }
//! }
//! ````
//!
//! As you can see, in the case of using `#[handler]`, the code becomes much simpler:
//! - No need to manually add `#[async_trait]`.
//! - The parameters that are not needed in the function have been omitted, and the required parameters can be arranged in any order.
//! - For objects that implement `Writer` or `Scribe` abstraction, it can be directly used as the return value of the function. Here `&'static str` implements `Scribe`, so it can be returned directly as the return value of the function.
//!
//! `#[handler]` can not only be added to the function, but also can be added to the `impl` of `struct` to let `struct` implement `Handler`. At this time, the `handle` function in the `impl` code block will be Identified as the specific implementation of `handle` in `Handler`:
//!
//! ```
//! use salvo_core::prelude::*;
//!
//! struct Hello;
//!
//! #[handler]
//! impl Hello {
//! async fn handle(&self, res: &mut Response) {
//! res.render(Text::Plain("hello world!"));
//! }
//! }
//! ````
//!
//! ## Handle errors
//!
//! `Handler` in Salvo can return `Result`, only the types of `Ok` and `Err` in `Result` are implemented `Writer` trait.
//!
//! Taking into account the widespread use of `anyhow`, the `Writer` implementation of `anyhow::Error` is provided by
//! default if `anyhow` feature is enabled, and `anyhow::Error` is Mapped to `InternalServerError`.
//!
//! For custom error types, you can output different error pages according to your needs.
//!
//! ```ignore
//! use anyhow::anyhow;
//! use salvo_core::prelude::*;
//!
//! struct CustomError;
//! #[async_trait]
//! impl Writer for CustomError {
//! async fn write(self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
//! res.status_code(StatusCode::INTERNAL_SERVER_ERROR);
//! res.render("custom error");
//! }
//! }
//!
//! #[handler]
//! async fn handle_anyhow() -> Result<(), anyhow::Error> {
//! Err(anyhow::anyhow!("anyhow error"))
//! }
//! #[handler]
//! async fn handle_custom() -> Result<(), CustomError> {
//! Err(CustomError)
//! }
//!
//! #[tokio::main]
//! async fn main() {
//! let router = Router::new()
//! .push(Router::new().path("anyhow").get(handle_anyhow))
//! .push(Router::new().path("custom").get(handle_custom));
//! let acceptor = TcpListener::new("127.0.0.1:5800").bind().await;
//! Server::new(acceptor).serve(router).await;
//! }
//! ```
//!
//! ## Implement Handler trait directly
//!
//! Under certain circumstances, We need to implment `Handler` direclty.
//!
//! ```
//! use salvo_core::prelude::*;
//! use crate::salvo_core::http::Body;
//!
//! pub struct MaxSizeHandler(u64);
//! #[async_trait]
//! impl Handler for MaxSizeHandler {
//! async fn handle(&self, req: &mut Request, _depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
//! if let Some(upper) = req.body().size_hint().upper() {
//! if upper > self.0 {
//! res.render(StatusError::payload_too_large());
//! ctrl.skip_rest();
//! }
//! }
//! }
//! }
//! ```
use crate::http::StatusCode;
use crate::{async_trait, Depot, FlowCtrl, Request, Response};
/// `Handler` is used for handle [`Request`].
///
/// View [module level documentation](index.html) for more details.
#[async_trait]
pub trait Handler: Send + Sync + 'static {
#[doc(hidden)]
fn type_id(&self) -> std::any::TypeId {
std::any::TypeId::of::<Self>()
}
#[doc(hidden)]
fn type_name(&self) -> &'static str {
std::any::type_name::<Self>()
}
/// Handle http request.
#[must_use = "handle future must be used"]
async fn handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl);
}
#[doc(hidden)]
pub struct EmptyHandler;
#[async_trait]
impl Handler for EmptyHandler {
async fn handle(&self, _req: &mut Request, _depot: &mut Depot, res: &mut Response, _ctrl: &mut FlowCtrl) {
res.status_code(StatusCode::OK);
}
}
/// This is a empty implement for `Handler`.
///
/// `EmptyHandler` does nothing except set [`Response`]'s satus as [`StatusCode::OK`], it just marker a router exits.
pub fn empty() -> EmptyHandler {
EmptyHandler
}
#[doc(hidden)]
#[non_exhaustive]
pub struct WhenHoop<H, F> {
pub inner: H,
pub filter: F,
}
#[async_trait]
impl<H, F> Handler for WhenHoop<H, F>
where
H: Handler,
F: Fn(&Request, &Depot) -> bool + Send + Sync + 'static,
{
async fn handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
if (self.filter)(req, depot) {
self.inner.handle(req, depot, res, ctrl).await;
}
}
}
/// `Skipper` is used to check if the request should be skipped.
///
/// `Skipper` is used in many middlewares.
pub trait Skipper: Send + Sync + 'static {
/// Check if the request should be skipped.
fn skipped(&self, req: &mut Request, depot: &Depot) -> bool;
}
impl<F> Skipper for F
where
F: Fn(&mut Request, &Depot) -> bool + Send + Sync + 'static,
{
fn skipped(&self, req: &mut Request, depot: &Depot) -> bool {
(self)(req, depot)
}
}
/// `none_skipper` will skipper nothing.
///
/// It can be used as default `Skipper` in middleware.
pub fn none_skipper(_req: &mut Request, _depot: &Depot) -> bool {
false
}
macro_rules! handler_tuple_impls {
($(
$Tuple:tt {
$(($idx:tt) -> $T:ident,)+
}
)+) => {$(
#[async_trait::async_trait]
impl<$($T,)+> Handler for ($($T,)+) where $($T: Handler,)+
{
async fn handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
$(
if !res.is_stamped() {
self.$idx.handle(req, depot, res, ctrl).await;
}
)+
}
})+
}
}
macro_rules! skipper_tuple_impls {
($(
$Tuple:tt {
$(($idx:tt) -> $T:ident,)+
}
)+) => {$(
impl<$($T,)+> Skipper for ($($T,)+) where $($T: Skipper,)+
{
fn skipped(&self, req: &mut Request, depot: &Depot) -> bool {
$(
if self.$idx.skipped(req, depot) {
return true;
}
)+
false
}
})+
}
}
macro_rules! __for_each_tuple {
($callback:ident) => {
$callback! {
1 {
(0) -> A,
}
2 {
(0) -> A,
(1) -> B,
}
3 {
(0) -> A,
(1) -> B,
(2) -> C,
}
4 {
(0) -> A,
(1) -> B,
(2) -> C,
(3) -> D,
}
5 {
(0) -> A,
(1) -> B,
(2) -> C,
(3) -> D,
(4) -> E,
}
6 {
(0) -> A,
(1) -> B,
(2) -> C,
(3) -> D,
(4) -> E,
(5) -> F,
}
7 {
(0) -> A,
(1) -> B,
(2) -> C,
(3) -> D,
(4) -> E,
(5) -> F,
(6) -> G,
}
8 {
(0) -> A,
(1) -> B,
(2) -> C,
(3) -> D,
(4) -> E,
(5) -> F,
(6) -> G,
(7) -> H,
}
}
};
}
__for_each_tuple!(handler_tuple_impls);
__for_each_tuple!(skipper_tuple_impls);