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
use error;
use response::{Context, Response, Serializer};
use util::BufStream;

use bytes::Bytes;
use http;
use http::header::{self, HeaderValue};
use serde_json::{self, Value};

impl Response for Value {
    type Buf = <Self::Body as BufStream>::Item;
    type Body = error::Map<Bytes>;

    fn into_http<S>(self, context: &Context<S>) -> Result<http::Response<Self::Body>, ::Error>
    where
        S: Serializer,
    {
        // TODO: Improve error handling
        let body = serde_json::to_vec(&self).unwrap();

        // TODO: Improve and handle errors
        let body = error::Map::new(Bytes::from(body));

        let mut response = http::Response::builder()
            // Customize response
            .status(200)
            .body(body)
            .unwrap();

        response
            .headers_mut()
            .entry(header::CONTENT_TYPE)
            .unwrap()
            .or_insert_with(|| {
                context.content_type_header()
                    .map(|content_type| content_type.clone())
                    .unwrap_or_else(|| {
                        HeaderValue::from_static("application/json")
                    })
            });

        Ok(response)
    }
}