tower_web/response/
serde.rs1use error;
2use response::{Response, Serializer, Context};
3use util::BufStream;
4
5use bytes::Bytes;
6use http::{self, header};
7use serde;
8
9#[derive(Debug)]
13pub struct SerdeResponse<T>(T);
14
15impl<T> SerdeResponse<T> {
16 pub fn new(value: T) -> SerdeResponse<T> {
18 SerdeResponse(value)
19 }
20}
21
22impl<T> Response for SerdeResponse<T>
23where
24 T: serde::Serialize,
25{
26 type Buf = <Self::Body as BufStream>::Item;
27 type Body = error::Map<Bytes>;
28
29 fn into_http<S>(self, context: &Context<S>) -> Result<http::Response<Self::Body>, ::Error>
30 where
31 S: Serializer,
32 {
33 let content_type = context.content_type_header()
34 .expect("no content type specified for response");
35
36 let serialize_context = context.serializer_context();
37
38 let serialized = context.serialize(&self.0, &serialize_context)
39 .unwrap();
41
42 let body = error::Map::new(serialized);
43
44 let mut response = http::Response::builder()
45 .status(200)
47 .body(body)
48 .unwrap();
49
50 response
51 .headers_mut()
52 .entry(header::CONTENT_TYPE)
53 .unwrap()
54 .or_insert_with(|| content_type.clone());
55
56 Ok(response)
57 }
58}