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
#![allow(clippy::let_and_return)]
use crate::{http_context::HttpContext, response::Builder};
use http::StatusCode;

macro_rules! impl_status_responder {
    ( $( $x:ty ),+ ) => {
        $(
            impl Responder for $x {
                fn respond_with_builder(self, builder: Builder, _ctx: &HttpContext) -> Builder {
                    builder.status(self as u16)
                }
            }
        )+
    }
}

macro_rules! impl_body_responder {
    ( $( $x:ty ),+ ) => {
        $(
            impl Responder for $x {
                fn respond_with_builder(self, builder: Builder, _ctx: &HttpContext) -> Builder {
                    builder.body(self)
                }
            }
        )+
    }
}

macro_rules! impl_plain_body_responder {
    ( $( $x:ty ),+ ) => {
        $(
            impl Responder for $x {
                fn respond_with_builder(self, builder: Builder, _ctx: &HttpContext) -> Builder {
                    builder.header(http::header::CONTENT_TYPE, "text/plain").body(self)
                }
            }
        )+
    }
}

macro_rules! impl_tuple_responder {

    ( $($idx:tt -> $T:ident),+ ) => {

            impl<$($T:Responder),+> Responder for ($($T),+) {
                fn respond_with_builder(self, builder: Builder, ctx: &HttpContext) -> Builder {
                    $(let builder = self.$idx.respond_with_builder(builder, ctx);)+
                    builder
                }
            }
    }
}

/// Responder defines what type can generate a response
pub trait Responder {
    /// Consume self into a builder
    ///
    /// ```rust
    /// # use saphir::prelude::*;
    /// struct CustomResponder(String);
    ///
    /// impl Responder for CustomResponder {
    ///     fn respond_with_builder(self, builder: Builder, ctx: &HttpContext) -> Builder {
    ///         // Put the string as the response body
    ///         builder.body(self.0)
    ///     }
    /// }
    /// ```
    fn respond_with_builder(self, builder: Builder, ctx: &HttpContext) -> Builder;
}

impl<T> Responder for Vec<T>
where
    T: Responder,
{
    fn respond_with_builder(self, mut builder: Builder, ctx: &HttpContext) -> Builder {
        for responder in self {
            builder = responder.respond_with_builder(builder, ctx);
        }
        builder
    }
}

impl<T> Responder for &'static [T]
where
    T: Responder + Clone,
{
    fn respond_with_builder(self, mut builder: Builder, ctx: &HttpContext) -> Builder {
        for responder in self {
            builder = responder.clone().respond_with_builder(builder, ctx);
        }
        builder
    }
}

impl Responder for StatusCode {
    fn respond_with_builder(self, builder: Builder, _ctx: &HttpContext) -> Builder {
        builder.status(self)
    }
}

impl Responder for () {
    fn respond_with_builder(self, builder: Builder, _ctx: &HttpContext) -> Builder {
        builder.status(200)
    }
}

impl<T: Responder> Responder for Option<T> {
    fn respond_with_builder(self, builder: Builder, ctx: &HttpContext) -> Builder {
        if let Some(r) = self {
            r.respond_with_builder(builder, ctx).status_if_not_set(200)
        } else {
            builder.status_if_not_set(404)
        }
    }
}

impl<T: Responder, E: Responder> Responder for Result<T, E> {
    fn respond_with_builder(self, builder: Builder, ctx: &HttpContext) -> Builder {
        match self {
            Ok(r) => r.respond_with_builder(builder, ctx).status_if_not_set(200),
            Err(r) => r.respond_with_builder(builder, ctx).status_if_not_set(500),
        }
    }
}

impl Responder for hyper::Error {
    fn respond_with_builder(self, builder: Builder, _ctx: &HttpContext) -> Builder {
        builder.status(500)
    }
}

impl Responder for Builder {
    fn respond_with_builder(self, _builder: Builder, _ctx: &HttpContext) -> Builder {
        self
    }
}

#[cfg(feature = "json")]
mod json {
    use super::*;
    use crate::body::Json;
    use serde::Serialize;

    impl<T: Serialize> Responder for Json<T> {
        fn respond_with_builder(self, builder: Builder, _ctx: &HttpContext) -> Builder {
            let b = match builder.json(&self.0) {
                Ok(b) => b,
                Err((b, _e)) => b.status(500).body("Unable to serialize json data"),
            };
            b.header(http::header::CONTENT_TYPE, "application/json")
        }
    }
}

#[cfg(feature = "form")]
mod form {
    use super::*;
    use crate::body::Form;
    use serde::Serialize;

    impl<T: Serialize> Responder for Form<T> {
        fn respond_with_builder(self, builder: Builder, _ctx: &HttpContext) -> Builder {
            let b = match builder.form(&self.0) {
                Ok(b) => b,
                Err((b, _e)) => b.status(500).body("Unable to serialize form data"),
            };
            b.header(http::header::CONTENT_TYPE, "application/x-www-form-urlencoded")
        }
    }
}

impl_status_responder!(u16, i16, u32, i32, u64, i64, usize, isize);
impl_plain_body_responder!(String, &'static str);
impl_body_responder!(Vec<u8>, &'static [u8], hyper::body::Bytes);
impl_tuple_responder!(0->A, 1->B);
impl_tuple_responder!(0->A, 1->B, 2->C);
impl_tuple_responder!(0->A, 1->B, 2->C, 3->D);
impl_tuple_responder!(0->A, 1->B, 2->C, 3->D, 4->E);
impl_tuple_responder!(0->A, 1->B, 2->C, 3->D, 4->E, 5->F);

/// Trait used by the server, not meant for manual implementation
pub trait DynResponder {
    #[doc(hidden)]
    fn dyn_respond(&mut self, builder: Builder, ctx: &HttpContext) -> Builder;
}

impl<T> DynResponder for Option<T>
where
    T: Responder,
{
    fn dyn_respond(&mut self, builder: Builder, ctx: &HttpContext) -> Builder {
        self.take().ok_or(500).respond_with_builder(builder, ctx)
    }
}