Skip to main content

glacier/
handler.rs

1//! Request handlers.
2
3use std::future::Future;
4use std::pin::Pin;
5
6use crate::context::Context;
7use crate::response::{IntoResponse, Response};
8
9pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
10
11/// Something that turns a request into a response.
12///
13/// Implemented for any `async fn(Context) -> impl IntoResponse`, so plain
14/// functions and closures can be used as route handlers.
15pub trait Handler: Send + Sync + 'static {
16    fn call(&self, ctx: Context) -> BoxFuture<Response>;
17}
18
19impl<F, Fut, R> Handler for F
20where
21    F: Fn(Context) -> Fut + Send + Sync + 'static,
22    Fut: Future<Output = R> + Send + 'static,
23    R: IntoResponse,
24{
25    fn call(&self, ctx: Context) -> BoxFuture<Response> {
26        let fut = self(ctx);
27        Box::pin(async move { fut.await.into_response() })
28    }
29}