Skip to main content

trillium_api/
from_conn.rs

1use crate::TryFromConn;
2use std::future::Future;
3use trillium::Conn;
4
5/// A trait to extract content from [`Conn`]s to be used as the second
6/// argument to an api handler. Implement this for your types.
7pub trait FromConn: Send + Sync + Sized + 'static {
8    /// returning None from this will not call the api handler, but
9    /// will halt the conn.
10    fn from_conn(conn: &mut Conn) -> impl Future<Output = Option<Self>> + Send;
11}
12
13impl FromConn for () {
14    async fn from_conn(_: &mut Conn) -> Option<Self> {
15        Some(())
16    }
17}
18
19impl<E: FromConn> FromConn for Option<E> {
20    async fn from_conn(conn: &mut Conn) -> Option<Self> {
21        Some(E::from_conn(conn).await)
22    }
23}
24
25impl<T, E> FromConn for Result<T, E>
26where
27    T: TryFromConn<Error = E>,
28    E: Send + Sync + 'static,
29{
30    async fn from_conn(conn: &mut Conn) -> Option<Self> {
31        Some(T::try_from_conn(conn).await)
32    }
33}
34
35impl FromConn for trillium::Headers {
36    async fn from_conn(conn: &mut Conn) -> Option<Self> {
37        Some(conn.request_headers().clone())
38    }
39}
40
41impl FromConn for trillium::Method {
42    async fn from_conn(conn: &mut Conn) -> Option<Self> {
43        Some(conn.method())
44    }
45}
46
47impl FromConn for trillium::Version {
48    async fn from_conn(conn: &mut Conn) -> Option<Self> {
49        Some(conn.http_version())
50    }
51}