Skip to main content

rustlavel_http/
handler.rs

1use crate::request::Request;
2use crate::response::{IntoResponse, Response};
3use std::future::Future;
4use std::pin::Pin;
5
6/// A boxed, owned future — the shape every handler and middleware returns.
7pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
8
9/// Anything that can answer a request.
10///
11/// Implemented for every `async fn(Request) -> impl IntoResponse`, so an
12/// application never names this trait: it just writes a function.
13pub trait Handler: Send + Sync + 'static {
14    fn call(&self, request: Request) -> BoxFuture<Response>;
15}
16
17impl<F, Fut, R> Handler for F
18where
19    F: Fn(Request) -> Fut + Send + Sync + 'static,
20    Fut: Future<Output = R> + Send + 'static,
21    R: IntoResponse + 'static,
22{
23    fn call(&self, request: Request) -> BoxFuture<Response> {
24        let future = self(request);
25        Box::pin(async move { future.await.into_response() })
26    }
27}
28
29/// A handler that always answers with the same response, for redirects and
30/// static pages registered straight on the router.
31pub struct Fixed(pub Response);
32
33impl Handler for Fixed {
34    fn call(&self, _request: Request) -> BoxFuture<Response> {
35        let response = self.0.clone();
36        Box::pin(async move { response })
37    }
38}