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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#[cfg(feature = "download")]
use crate::download::{ContentDisposition, DispositionType};
use crate::{body::HttpBody, error::Error, responder::Responder};
#[cfg(feature = "cookie")]
use cookie::CookieJar;
use headers::{Header, HeaderMapExt};
use hyper::{
    body::Bytes,
    http::{self, HeaderMap, HeaderName, HeaderValue},
    StatusCode,
};
use serde::Serialize;
use std::ops::{Deref, DerefMut};

#[derive(Default)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub struct Response {
    #[doc(hidden)]
    inner: hyper::Response<HttpBody>,
    #[doc(hidden)]
    status_set: bool,
    #[doc(hidden)]
    #[cfg(feature = "cookie")]
    cookies: CookieJar,
}
impl Response {
    #[inline]
    pub fn new(
        inner: hyper::Response<HttpBody>,
        status_set: bool,
        #[cfg(feature = "cookie")] cookies: CookieJar,
    ) -> Self {
        Response {
            inner,
            status_set,
            #[cfg(feature = "cookie")]
            cookies,
        }
    }
    /// Add cookie
    #[cfg(feature = "cookie")]
    #[inline]
    pub fn cookie(&mut self, cookie: cookie::Cookie<'static>) -> &mut Self {
        self.cookies.add(cookie);
        self
    }
    #[cfg(feature = "cookie")]
    #[inline]
    pub fn cookies(&self) -> &CookieJar {
        &self.cookies
    }
    #[cfg(feature = "cookie")]
    #[inline]
    pub fn cookies_mut(&mut self) -> &mut CookieJar {
        &mut self.cookies
    }
    /// Removes `cookie` from this [`CookieJar`].
    /// Read more about [removal cookies](https://docs.rs/cookie/0.18.0/cookie/struct.CookieJar.html#method.remove).
    #[cfg(feature = "cookie")]
    #[inline]
    pub fn cookie_remove(&mut self, name: &str) -> &mut Self {
        if let Some(cookie) = self.cookies.get(name).cloned() {
            self.cookies.remove(cookie);
        }
        self
    }
    /// Appends a header to this response builder.
    ///
    /// This function will append the provided key/value as a header to the
    /// internal `HeaderMap` being constructed. Essentially this is equivalent
    /// to calling `HeaderMap::append`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use hypers::prelude::Response;
    ///
    /// let response = Response::default()
    ///     .header("Content-Type", "text/html")
    ///     .header("X-Custom-Foo", "bar")
    ///     .header("content-length", 0)
    ///     .body("");
    /// ```
    #[inline]
    pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self
    where
        HeaderName: TryFrom<K>,
        <HeaderName as TryFrom<K>>::Error: Into<http::Error>,
        HeaderValue: TryFrom<V>,
        <HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
    {
        let name = <HeaderName as TryFrom<K>>::try_from(key)
            .map_err(Into::into)
            .expect("Invalid key");
        let value = <HeaderValue as TryFrom<V>>::try_from(value)
            .map_err(Into::into)
            .expect("Invalid value");
        self.inner.headers_mut().append(name, value);
        self
    }
    #[inline]
    pub fn header_set<H: Header>(&mut self, h: H) -> &mut Self {
        self.inner.headers_mut().typed_insert(h);
        self
    }
    #[inline]
    pub(crate) fn status_if_not_set<T>(&mut self, status: T) -> &mut Self
    where
        StatusCode: TryFrom<T>,
        <StatusCode as TryFrom<T>>::Error: Into<http::Error>,
    {
        if !self.status_set {
            self.status(status)
        } else {
            self
        }
    }
    #[inline]
    pub fn status<T>(&mut self, status: T) -> &mut Self
    where
        StatusCode: TryFrom<T>,
        <StatusCode as TryFrom<T>>::Error: Into<http::Error>,
    {
        self.status_set = true;
        *self.inner.status_mut() = TryFrom::try_from(status)
            .map_err(Into::into)
            .expect("error");
        self
    }
    /// The response redirects to the specified URL.
    ///
    /// [mdn]: <https://developer.mozilla.org/en-US/docs/Web/API/Response/redirect>
    #[inline]
    pub fn redirect<T>(&mut self, status: T, url: &str) -> &mut Self
    where
        StatusCode: TryFrom<T>,
        <StatusCode as TryFrom<T>>::Error: Into<http::Error>,
    {
        let value = http::header::HeaderValue::try_from(url).expect("url is not the correct value");
        self.status_set = true;
        *self.inner.status_mut() = TryFrom::try_from(status)
            .map_err(Into::into)
            .expect("error");
        self.inner
            .headers_mut()
            .append(http::header::LOCATION, value);
        self
    }
    /// The [`Content-Location`][mdn] header indicates an alternate location for the returned data.
    ///
    /// [mdn]: <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Location>
    #[inline]
    pub fn location(&mut self, location: &str) -> &mut Self {
        let value = http::header::HeaderValue::try_from(location)
            .expect("location is not the correct value");
        self.inner
            .headers_mut()
            .append(http::header::CONTENT_LOCATION, value);
        self
    }
    /// Write bytes data to body
    #[inline]
    pub fn body(&mut self, data: impl Into<Bytes>) -> &mut Self {
        let body: Bytes = data.into();
        let body: HttpBody = body.into();
        *self.inner.body_mut() = body;
        self
    }
    /// The response with the specified [`Content-Type`][mdn].
    ///
    /// [mdn]: <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type>
    #[inline]
    pub fn content_type(&mut self, content_type: &str) -> &mut Self {
        if let Ok(c_type) = HeaderValue::from_str(content_type) {
            self.inner.headers_mut().insert("content-type", c_type);
        }
        self
    }
    /// The response with `text/html; charset=utf-8` media type.
    #[inline]
    pub fn html<T: Into<Bytes>>(&mut self, value: T) -> &mut Self {
        self.content_type("text/html; charset=utf-8").body(value)
    }
    /// The response with `text/plain; charset=utf-8` media type.
    #[inline]
    pub fn text<T: Into<Bytes>>(&mut self, value: T) -> &mut Self {
        self.content_type("text/plain; charset=utf-8").body(value)
    }
    /// The response with `application/json; charset=utf-8` media type.
    #[inline]
    pub fn json<T: Serialize>(&mut self, value: &T) -> &mut Self {
        match serde_json::to_vec(value) {
            Ok(v) => self.content_type("application/json").body(v),
            Err(e) => self
                .status_if_not_set(StatusCode::INTERNAL_SERVER_ERROR)
                .text(e.to_string()),
        }
    }
    /// The response with `application/json; charset=utf-8` media type.
    #[inline]
    pub fn json_pretty<T: Serialize>(&mut self, value: &T) -> &mut Self {
        match serde_json::to_vec_pretty(value) {
            Ok(v) => self.content_type("application/json").body(v),
            Err(e) => self
                .status_if_not_set(StatusCode::INTERNAL_SERVER_ERROR)
                .text(e.to_string()),
        }
    }
    /// The response with `application/x-www-form-urlencoded; charset=utf-8` media type.
    #[inline]
    pub fn form<T: Serialize>(&mut self, value: &T) -> &mut Self {
        match serde_urlencoded::to_string(value) {
            Ok(v) => self
                .content_type("application/x-www-form-urlencoded")
                .body(v),
            Err(e) => self
                .status_if_not_set(StatusCode::INTERNAL_SERVER_ERROR)
                .text(e.to_string()),
        }
    }
    /// Render content.
    /// # Example
    /// ```
    /// use hypers::prelude::Response;
    ///
    /// let mut res = Response::default();
    /// res.render("hello world");
    /// ```
    #[inline]
    pub fn render<R>(&mut self, responder: R)
    where
        R: Responder,
    {
        responder.response(self)
    }
    /// Responds to a stream.
    #[inline]
    pub fn stream<S, O, E>(&mut self, stream: S) -> &mut Self
    where
        S: futures::Stream<Item = Result<O, E>> + Send + Sync + 'static,
        O: Into<Bytes> + 'static,
        E: Into<Error> + 'static,
    {
        *self.inner.body_mut() = HttpBody::stream(stream);
        self
    }
    /// Attempts to send a file. If file not exists, not found error will occur.
    #[inline]
    pub async fn send_file<P>(&mut self, path: P, req_headers: &HeaderMap) -> &mut Self
    where
        P: Into<std::path::PathBuf> + Send,
    {
        let path = path.into();
        if !path.exists() {
            self.status(StatusCode::NOT_FOUND)
        } else {
            match crate::fs::NamedFile::builder(path).build().await {
                Ok(file) => {
                    file.send(req_headers, self).await;
                    self
                }
                Err(_) => self.status(StatusCode::INTERNAL_SERVER_ERROR),
            }
        }
    }
    #[cfg(feature = "download")]
    #[inline]
    pub fn write_file(
        &mut self,
        path: impl AsRef<std::path::Path>,
        disposition_type: DispositionType,
    ) -> Result<&mut Self, Error> {
        let path = path.as_ref();
        let mut file = std::fs::File::open(path)?;
        let mut buffer = Vec::new();
        use std::io::Read;
        file.read_to_end(&mut buffer)?;
        if let Some(filename) = path.file_name() {
            let name = filename.to_string_lossy();
            let content_disposition =
                ContentDisposition::new(disposition_type, Some(&name)).try_into()?;
            self.inner
                .headers_mut()
                .insert("content-disposition", content_disposition);
        }
        let body: Bytes = buffer.into();
        let body: HttpBody = body.into();
        *self.inner.body_mut() = body;
        Ok(self)
    }
    #[allow(unused_mut)]
    #[inline]
    pub fn into_raw(self) -> Result<hyper::Response<HttpBody>, Error> {
        let Response {
            mut inner,
            #[cfg(feature = "cookie")]
            cookies,
            ..
        } = self;
        #[cfg(feature = "cookie")]
        for c in cookies.iter() {
            inner.headers_mut().append(
                http::header::SET_COOKIE,
                http::HeaderValue::from_str(c.to_string().as_str())?,
            );
        }
        Ok(inner)
    }
    #[inline]
    pub fn map<F>(self, f: F) -> Response
    where
        F: FnOnce(HttpBody) -> HttpBody,
    {
        let inner = self.inner.map(f);
        Response {
            inner,
            status_set: self.status_set,
            #[cfg(feature = "cookie")]
            cookies: self.cookies,
        }
    }
}
impl Deref for Response {
    type Target = hyper::Response<HttpBody>;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}
impl DerefMut for Response {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}