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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use std::borrow::Cow;
use std::error::Error as StdError;
use std::fmt::{self, Debug};
use std::pin::Pin;
use std::task::{self, Poll};

use bytes::{Bytes, BytesMut};
use cookie::{Cookie, CookieJar};
use futures::{Stream, TryStreamExt};
use hyper::Method;
use serde::{Deserialize, Serialize};
use http::version::Version;

use super::errors::*;
use super::header::{self, HeaderMap, HeaderValue, InvalidHeaderValue, SET_COOKIE};
use crate::http::{Request, StatusCode};

#[allow(clippy::type_complexity)]
pub enum Body {
    Empty,
    Bytes(BytesMut),
    Stream(Pin<Box<dyn Stream<Item = Result<Bytes, Box<dyn StdError + Send + Sync>>> + Send>>),
}

impl Stream for Body {
    type Item = Result<Bytes, Box<dyn StdError + Send + Sync>>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
        match self.get_mut() {
            Body::Empty => Poll::Ready(None),
            Body::Bytes(bytes) => Poll::Ready(Some(Ok(bytes.clone().freeze()))),
            Body::Stream(stream) => {
                let x = stream.as_mut();
                x.poll_next(cx)
            }
        }
    }
}
impl From<hyper::Body> for Body {
    fn from(hbody: hyper::Body) -> Body {
        Body::Stream(Box::pin(hbody.map_err(|e|e.into_cause().unwrap()).into_stream()))
    }
}
/// The response representation given to `Middleware`
pub struct Response {
    /// The response status-code.
    status_code: Option<StatusCode>,
    pub(crate) http_error: Option<HttpError>,
    /// The headers of the response.
    headers: HeaderMap,
    version: Version,
    pub(crate) cookies: CookieJar,
    pub(crate) body: Option<Body>,
    is_commited: bool,
}

impl Response {
    pub fn new() -> Response {
        Response {
            status_code: None,
            http_error: None,
            body: None,
            version: Version::default(),
            headers: HeaderMap::new(),
            cookies: CookieJar::new(),
            is_commited: false,
        }
    }
    /// Create a request from an hyper::Request.
    ///
    /// This constructor consumes the hyper::Request.
    pub fn from_hyper(req: hyper::Response<hyper::Body>) -> Response {
        let (
            http::response::Parts {
                status,
                version,
                headers,
                // extensions,
                ..
            },
            body,
        ) = req.into_parts();

        // Set the request cookies, if they exist.
        let cookies = if let Some(header) = headers.get("Cookie") {
            let mut cookie_jar = CookieJar::new();
            if let Ok(header) = header.to_str() {
                for cookie_str in header.split(';').map(|s| s.trim()) {
                    if let Ok(cookie) = Cookie::parse_encoded(cookie_str).map(|c| c.into_owned()) {
                        cookie_jar.add_original(cookie);
                    }
                }
            }
            cookie_jar
        } else {
            CookieJar::new()
        };

        Response {
            status_code: Some(status),
            http_error: None,
            body: Some(body.into()),
            version: version,
            headers,
            cookies,
            is_commited: false,
        }
    }

    #[inline(always)]
    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }
    #[inline(always)]
    pub fn headers_mut(&mut self) -> &mut HeaderMap {
        &mut self.headers
    }
    #[inline(always)]
    pub fn set_headers(&mut self, headers: HeaderMap) {
        self.headers = headers
    }
    
    #[inline]
    pub fn version(&self) -> Version {
        self.version
    }

    #[inline]
    pub fn version_mut(&mut self) -> &mut Version {
        &mut self.version
    }

    #[inline(always)]
    pub fn body(&self) -> Option<&Body> {
        self.body.as_ref()
    }
    #[inline(always)]
    pub fn body_mut(&mut self) -> Option<&mut Body> {
        self.body.as_mut()
    }
    #[inline(always)]
    pub fn set_body(&mut self, body: Option<Body>) {
        self.body = body
    }
    #[inline(always)]
    pub fn take_body(&mut self) -> Option<Body> {
        self.body.take()
    }
    // pub fn insert_header<K>(&mut self, key: K, val: T) -> Option<T> where K: IntoHeaderName,
    //     self.headers.insert(key, val)
    // }

    // `write_back` is used to put all the data added to `self`
    // back onto an `hyper::Response` so that it is sent back to the
    // client.
    //
    // `write_back` consumes the `Response`.
    pub(crate) async fn write_back(self, req: &mut Request, res: &mut hyper::Response<hyper::Body>) {
        *res.headers_mut() = self.headers;

        // Default to a 404 if no response code was set
        *res.status_mut() = self.status_code.unwrap_or(StatusCode::NOT_FOUND);

        if let Method::HEAD = *req.method() {
        } else if let Some(body) = self.body {
            match body {
                Body::Bytes(bytes) => {
                    *res.body_mut() = hyper::Body::from(Bytes::from(bytes));
                }
                Body::Stream(stream) => {
                    *res.body_mut() = hyper::Body::wrap_stream(stream);
                }
                _ => {
                    res.headers_mut().insert(header::CONTENT_LENGTH, header::HeaderValue::from_static("0"));
                }
            }
        } else {
            res.headers_mut().insert(header::CONTENT_LENGTH, header::HeaderValue::from_static("0"));
        }
    }

    #[inline(always)]
    pub fn cookies(&self) -> &CookieJar {
        &self.cookies
    }
    pub fn header_cookies(&self) -> Vec<Cookie<'_>> {
        let mut cookies = vec![];
        for header in self.headers().get_all(header::SET_COOKIE).iter() {
            if let Ok(header) = header.to_str() {
                if let Ok(cookie) = Cookie::parse_encoded(header) {
                    cookies.push(cookie);
                }
            }
        }
        cookies
    }

    #[inline]
    pub fn get_cookie<T>(&self, name: T) -> Option<&Cookie<'static>>
    where
        T: AsRef<str>,
    {
        self.cookies.get(name.as_ref())
    }
    #[inline]
    pub fn add_cookie(&mut self, cookie: Cookie<'static>) {
        self.cookies.add(cookie);
    }
    #[inline]
    pub fn remove_cookie<T>(&mut self, name: T)
    where
        T: Into<Cow<'static, str>>,
    {
        self.cookies.remove(Cookie::named(name));
    }
    #[inline]
    pub fn status_code(&mut self) -> Option<StatusCode> {
        self.status_code
    }

    #[inline]
    pub fn set_status_code(&mut self, code: StatusCode) {
        let is_success = code.is_success();
        self.status_code = Some(code);
        if !is_success {
            self.commit();
        }
    }
    // #[inline(always)]
    // pub fn content_type(&self) -> Option<Mime> {
    //     self.headers.get_one("Content-Type").and_then(|v| v.parse().ok())
    // }

    #[inline]
    pub fn set_http_error(&mut self, err: HttpError) {
        self.status_code = Some(err.code);
        self.http_error = Some(err);
        self.commit();
    }
    #[inline]
    pub fn render_json<T: Serialize>(&mut self, data: &T) {
        if let Ok(data) = serde_json::to_string(data) {
            self.render_binary(HeaderValue::from_static("application/json; charset=utf-8"), data.as_bytes());
        } else {
            self.set_status_code(StatusCode::INTERNAL_SERVER_ERROR);
            let emsg = ErrorWrap::new("server_error", "server error", "error when serialize object to json");
            self.render_binary(
                HeaderValue::from_static("application/json; charset=utf-8"),
                serde_json::to_string(&emsg).unwrap().as_bytes(),
            );
        }
    }
    pub fn render_json_text(&mut self, data: &str) {
        self.render_binary(HeaderValue::from_static("application/json; charset=utf-8"), data.as_bytes());
    }
    #[inline]
    pub fn render_html_text(&mut self, data: &str) {
        self.render_binary(HeaderValue::from_static("text/html; charset=utf-8"), data.as_bytes());
    }
    #[inline]
    pub fn render_plain_text(&mut self, data: &str) {
        self.render_binary(HeaderValue::from_static("text/plain; charset=utf-8"), data.as_bytes());
    }
    #[inline]
    pub fn render_xml_text(&mut self, data: &str) {
        self.render_binary(HeaderValue::from_static("text/xml; charset=utf-8"), data.as_bytes());
    }
    // RenderBinary renders store from memory (which could be a file that has not been written,
    // the output from some function, or bytes streamed from somewhere else, as long
    // it implements io.Reader).  When called directly on something generated or
    // streamed, modtime should mostly likely be time.Now().
    #[inline]
    pub fn render_binary(&mut self, content_type: HeaderValue, data: &[u8]) {
        self.headers.insert(header::CONTENT_TYPE, content_type);
        self.write_body_bytes(data);
    }

    #[inline]
    pub fn write_body_bytes(&mut self, data: &[u8]) {
        if let Some(body) = self.body_mut() {
            match body {
                Body::Bytes(bytes) => {
                    bytes.extend_from_slice(data);
                }
                Body::Stream(_) => {
                    tracing::error!("current body kind is stream, try to write bytes to it");
                }
                _ => {
                    self.body = Some(Body::Bytes(BytesMut::from(data)));
                }
            }
        } else {
            self.body = Some(Body::Bytes(BytesMut::from(data)));
        }
    }
    #[inline]
    pub fn streaming<S, O, E>(&mut self, stream: S)
    where
        S: Stream<Item = Result<O, E>> + Send + 'static,
        O: Into<Bytes> + 'static,
        E: Into<Box<dyn StdError + Send + Sync>> + 'static,
    {
        if let Some(body) = &self.body {
            match body {
                Body::Bytes(_) => {
                    tracing::warn!("Current body kind is bytes already");
                }
                Body::Stream(_) => {
                    tracing::warn!("Current body kind is stream already");
                }
                _ => {}
            }
        }
        let mapped = stream.map_ok(Into::into).map_err(Into::into);
        self.body = Some(Body::Stream(Box::pin(mapped)));
    }

    #[inline]
    pub fn redirect_temporary<U: AsRef<str>>(&mut self, url: U) {
        self.status_code = Some(StatusCode::MOVED_PERMANENTLY);
        if !self.headers().contains_key(header::CONTENT_TYPE) {
            self.headers.insert(header::CONTENT_TYPE, "text/html".parse().unwrap());
        }
        self.headers.insert(header::LOCATION, url.as_ref().parse().unwrap());
        self.commit();
    }
    #[inline]
    pub fn redirect_found<U: AsRef<str>>(&mut self, url: U) {
        self.status_code = Some(StatusCode::FOUND);
        if !self.headers().contains_key(header::CONTENT_TYPE) {
            self.headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("text/html"));
        }
        self.headers.insert(header::LOCATION, url.as_ref().parse().unwrap());
        self.commit();
    }
    #[inline]
    pub fn redirect_other<U: AsRef<str>>(&mut self, url: U) -> Result<(), InvalidHeaderValue> {
        self.status_code = Some(StatusCode::SEE_OTHER);
        if !self.headers().contains_key(header::CONTENT_TYPE) {
            self.headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("text/html"));
        }
        self.headers.insert(header::LOCATION, url.as_ref().parse()?);
        self.commit();
        Ok(())
    }
    // #[inline]
    // pub fn set_content_disposition(&mut self, value: &str) -> Result<(), InvalidHeaderValue> {
    //     self.headers_mut().insert(CONTENT_DISPOSITION, value.parse()?);
    //     Ok(())
    // }
    // #[inline]
    // pub fn set_content_encoding(&mut self, value: &str) -> Result<(), InvalidHeaderValue> {
    //     self.headers_mut().insert(CONTENT_ENCODING, value.parse()?);
    //     Ok(())
    // }
    // #[inline]
    // pub fn set_content_length(&mut self, value: u64) -> Result<(), InvalidHeaderValue> {
    //     self.headers_mut().insert(CONTENT_LENGTH, value.to_string().parse()?);
    //     Ok(())
    // }
    // #[inline]
    // pub fn set_content_range(&mut self, value: &str) -> Result<(), InvalidHeaderValue> {
    //     self.headers_mut().insert(CONTENT_RANGE, value.parse()?);
    //     Ok(())
    // }
    // #[inline]
    // pub fn set_content_type(&mut self, value: &str) -> Result<(), InvalidHeaderValue> {
    //     self.headers_mut().insert(CONTENT_TYPE, value.parse()?);
    //     Ok(())
    // }
    // #[inline]
    // pub fn set_accept_range(&mut self, value: &str) -> Result<(), InvalidHeaderValue> {
    //     self.headers_mut().insert(ACCEPT_RANGES, value.parse()?);
    //     Ok(())
    // }
    // #[inline]
    // pub fn set_last_modified(&mut self, value: HttpDate) -> Result<(), InvalidHeaderValue> {
    //     self.headers_mut().insert(LAST_MODIFIED, format!("{}", value).parse()?);
    //     Ok(())
    // }
    // #[inline]
    // pub fn set_etag(&mut self, value: &str) -> Result<(), InvalidHeaderValue> {
    //     self.headers_mut().insert(ETAG, value.parse()?);
    //     Ok(())
    // }
    #[inline]
    pub fn commit(&mut self) {
        for cookie in self.cookies.delta() {
            if let Ok(hv) = cookie.encoded().to_string().parse() {
                self.headers.append(SET_COOKIE, hv);
            }
        }
        self.is_commited = true;
    }
    #[inline]
    pub fn is_commited(&self) -> bool {
        self.is_commited
    }
}

impl Debug for Response {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "HTTP/1.1 {}\n{:?}", self.status_code.unwrap_or(StatusCode::NOT_FOUND), self.headers)
    }
}

impl fmt::Display for Response {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

#[derive(Serialize, Deserialize, Debug)]
struct ErrorInfo {
    name: String,
    summary: String,
    detail: String,
}
#[derive(Serialize, Deserialize, Debug)]
struct ErrorWrap {
    error: ErrorInfo,
}

impl ErrorWrap {
    pub fn new<N, S, D>(name: N, summary: S, detail: D) -> ErrorWrap
    where
        N: Into<String>,
        S: Into<String>,
        D: Into<String>,
    {
        ErrorWrap {
            error: ErrorInfo {
                name: name.into(),
                summary: summary.into(),
                detail: detail.into(),
            },
        }
    }
}