logo
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
//! Writer trait and it's implements.
use async_trait::async_trait;
use serde::Serialize;

use crate::http::header::{HeaderValue, CONTENT_TYPE};
use crate::http::{Request, Response, StatusError};
use crate::Depot;

/// Writer is used to write data to response.
#[async_trait]
pub trait Writer {
    /// Write data to [`Response`].
    #[must_use = "write future must be used"]
    async fn write(mut self, req: &mut Request, depot: &mut Depot, res: &mut Response);
}

#[async_trait]
impl<T, E> Writer for Result<T, E>
where
    T: Writer + Send,
    E: Writer + Send,
{
    #[inline]
    async fn write(mut self, req: &mut Request, depot: &mut Depot, res: &mut Response) {
        match self {
            Ok(v) => {
                v.write(req, depot, res).await;
            }
            Err(e) => {
                e.write(req, depot, res).await;
            }
        }
    }
}

/// `Piece` is used to write data to [`Response`].
///
/// `Piece` is simpler than [`Writer`] ant it implements [`Writer`].
pub trait Piece {
    /// Render data to [`Response`].
    fn render(self, res: &mut Response);
}
#[async_trait]
impl<P> Writer for P
where
    P: Piece + Sized + Send,
{
    #[inline]
    async fn write(mut self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
        self.render(res)
    }
}

#[allow(clippy::unit_arg)]
impl Piece for () {
    #[inline]
    fn render(self, _res: &mut Response) {}
}
impl<'a> Piece for &'a str {
    #[inline]
    fn render(self, res: &mut Response) {
        res.headers_mut()
            .insert(CONTENT_TYPE, HeaderValue::from_static("text/plain; charset=utf-8"));
        res.write_body(self.as_bytes()).ok();
    }
}
impl<'a> Piece for &'a String {
    #[inline]
    fn render(self, res: &mut Response) {
        (&**self).render(res);
    }
}
impl Piece for String {
    #[inline]
    fn render(self, res: &mut Response) {
        (&*self).render(res);
    }
}

/// Write text content to response as text content.
pub enum Text<C> {
    /// It will set ```content-type``` to ```text/plain; charset=utf-8```.
    Plain(C),
    /// It will set ```content-type``` to ```application/json; charset=utf-8```.
    Json(C),
    /// It will set ```content-type``` to ```application/xml; charset=utf-8```.
    Xml(C),
    /// It will set ```content-type``` to ```text/html; charset=utf-8```.
    Html(C),
    /// It will set ```content-type``` to ```text/javascript; charset=utf-8```.
    Js(C),
    /// It will set ```content-type``` to ```text/css; charset=utf-8```.
    Css(C),
}
impl<C> Piece for Text<C>
where
    C: AsRef<str> + Send,
{
    #[inline]
    fn render(self, res: &mut Response) {
        let (ctype, content) = match self {
            Self::Plain(content) => (HeaderValue::from_static("text/plain; charset=utf-8"), content),
            Self::Json(content) => (HeaderValue::from_static("application/json; charset=utf-8"), content),
            Self::Xml(content) => (HeaderValue::from_static("application/xml; charset=utf-8"), content),
            Self::Html(content) => (HeaderValue::from_static("text/html; charset=utf-8"), content),
            Self::Js(content) => (HeaderValue::from_static("text/javascript; charset=utf-8"), content),
            Self::Css(content) => (HeaderValue::from_static("text/css; charset=utf-8"), content),
        };
        res.headers_mut().insert(CONTENT_TYPE, ctype);
        res.write_body(content.as_ref().as_bytes()).ok();
    }
}

/// Write serializable content to response as json content. It will set ```content-type``` to ```application/json; charset=utf-8```.
pub struct Json<T>(pub T);
#[async_trait]
impl<T> Piece for Json<T>
where
    T: Serialize + Send,
{
    #[inline]
    fn render(self, res: &mut Response) {
        match serde_json::to_vec(&self.0) {
            Ok(bytes) => {
                res.headers_mut().insert(
                    CONTENT_TYPE,
                    HeaderValue::from_static("application/json; charset=utf-8"),
                );
                res.write_body(&bytes).ok();
            }
            Err(e) => {
                tracing::error!(error = ?e, "JsonContent write error");
                res.set_status_error(StatusError::internal_server_error());
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::prelude::*;

    use super::*;

    async fn access(service: &Service) -> Response {
        let req: Request = hyper::Request::builder()
            .method("GET")
            .uri("http://127.0.0.1:7979/test")
            .body(hyper::Body::empty())
            .unwrap()
            .into();
        service.handle(req).await
    }

    #[tokio::test]
    async fn test_write_str() {
        #[fn_handler(internal)]
        async fn test() -> &'static str {
            "hello"
        }

        let router = Router::new().push(Router::with_path("test").get(test));
        let service = Service::new(router);

        let mut res = access(&service).await;
        assert_eq!(res.take_text().await.unwrap(), "hello");
        assert_eq!(res.headers().get("content-type").unwrap(), "text/plain; charset=utf-8");
    }

    #[tokio::test]
    async fn test_write_string() {
        #[fn_handler(internal)]
        async fn test() -> String {
            "hello".to_owned()
        }

        let router = Router::new().push(Router::with_path("test").get(test));
        let service = Service::new(router);

        let mut res = access(&service).await;
        assert_eq!(res.take_text().await.unwrap(), "hello");
        assert_eq!(res.headers().get("content-type").unwrap(), "text/plain; charset=utf-8");
    }

    #[tokio::test]
    async fn test_write_plain_text() {
        #[fn_handler(internal)]
        async fn test() -> Text<&'static str> {
            Text::Plain("hello")
        }

        let router = Router::new().push(Router::with_path("test").get(test));
        let service = Service::new(router);

        let mut res = access(&service).await;
        assert_eq!(res.take_text().await.unwrap(), "hello");
        assert_eq!(res.headers().get("content-type").unwrap(), "text/plain; charset=utf-8");
    }

    #[tokio::test]
    async fn test_write_json_text() {
        #[fn_handler(internal)]
        async fn test() -> Text<&'static str> {
            Text::Json(r#"{"hello": "world"}"#)
        }

        let router = Router::new().push(Router::with_path("test").get(test));
        let service = Service::new(router);

        let mut res = access(&service).await;
        assert_eq!(res.take_text().await.unwrap(), r#"{"hello": "world"}"#);
        assert_eq!(
            res.headers().get("content-type").unwrap(),
            "application/json; charset=utf-8"
        );
    }

    #[tokio::test]
    async fn test_write_json_content() {
        #[derive(Serialize, Debug)]
        struct User {
            name: String,
        }
        #[fn_handler(internal)]
        async fn test() -> Json<User> {
            Json(User { name: "jobs".into() })
        }

        let router = Router::new().push(Router::with_path("test").get(test));
        let service = Service::new(router);

        let mut res = access(&service).await;
        assert_eq!(res.take_text().await.unwrap(), r#"{"name":"jobs"}"#);
        assert_eq!(
            res.headers().get("content-type").unwrap(),
            "application/json; charset=utf-8"
        );
    }

    #[tokio::test]
    async fn test_write_html_text() {
        #[fn_handler(internal)]
        async fn test() -> Text<&'static str> {
            Text::Html("<html><body>hello</body></html>")
        }

        let router = Router::new().push(Router::with_path("test").get(test));
        let service = Service::new(router);

        let mut res = access(&service).await;
        assert_eq!(res.take_text().await.unwrap(), "<html><body>hello</body></html>");
        assert_eq!(res.headers().get("content-type").unwrap(), "text/html; charset=utf-8");
    }
}