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
//! An extension crate for roa.
//! This module provides a context extension `PowerBody`.
//!
//! ### Read/write body in a easier way.
//!
//! The `roa_core` provides several methods to read/write body.
//!
//! ```rust
//! use roa_core::{Context, Result};
//! use futures::AsyncReadExt;
//! use futures::io::BufReader;
//! use async_std::fs::File;
//!
//! async fn get(mut ctx: Context<()>) -> Result {
//!     let mut data = String::new();
//!     // implements futures::AsyncRead.
//!     ctx.req_mut().reader().read_to_string(&mut data).await?;
//!     println!("data: {}", data);
//!
//!     // although body is empty now...
//!     let stream = ctx.req_mut().stream();
//!     ctx.resp_mut()
//!         // echo
//!        .write_stream(stream)
//!        // write object implementing futures::AsyncRead
//!        .write_reader(File::open("assets/author.txt").await?)
//!        // write `Bytes`
//!        .write("I am Roa.")
//!        .write("Hey Roa.");
//!     Ok(())
//! }
//! ```
//!
//! These methods are useful, but they do not deal with headers, especially `Content-*` headers.
//!
//! The `PowerBody` provides more powerful methods to handle it.
//!
//! ```rust
//! use roa_core::{Context, Result};
//! use roa_body::{PowerBody, DispositionType::*};
//! use serde::{Serialize, Deserialize};
//! use askama::Template;
//! use async_std::fs::File;
//! use futures::io::BufReader;
//!
//! #[derive(Debug, Serialize, Deserialize, Template)]
//! #[template(path = "user.html")]
//! struct User {
//!     id: u64,
//!     name: String,
//! }
//!
//! async fn get(mut ctx: Context<()>) -> Result {
//!     // deserialize as json.
//!     let mut user: User = ctx.read_json().await?;
//!
//!     // deserialize as x-form-urlencoded.
//!     user = ctx.read_form().await?;
//!
//!     // serialize object and write it to body,
//!     // set "Content-Type"
//!     ctx.write_json(&user)?;
//!
//!     // open file and write it to body,
//!     // set "Content-Type" and "Content-Disposition"
//!     ctx.write_file("assets/welcome.html", Inline).await?;
//!
//!     // write text,
//!     // set "Content-Type"
//!     ctx.write_text("Hello, World!")?;
//!
//!     // write object implementing AsyncRead,
//!     // set "Content-Type"
//!     ctx.write_octet(File::open("assets/author.txt").await?)?;
//!
//!     // render html template, based on [askama](https://github.com/djc/askama).
//!     // set "Content-Type"
//!     ctx.render(&user)?;
//!     Ok(())
//! }
//! ```

mod content_type;
mod help;
use bytes::{Bytes, BytesMut};
use content_type::{Content, ContentType};
use futures::{AsyncRead, StreamExt};
use roa_core::{async_trait, http, Context, Result, State};

#[cfg(feature = "json")]
mod decode;
#[cfg(feature = "json")]
mod json;
#[cfg(feature = "urlencoded")]
mod urlencoded;
#[cfg(feature = "template")]
use askama::Template;
#[cfg(feature = "file")]
mod file;
#[cfg(feature = "file")]
pub use file::DispositionType;
#[cfg(feature = "file")]
use file::{write_file, Path};
#[cfg(any(feature = "json", feature = "urlencoded"))]
use serde::de::DeserializeOwned;

#[cfg(feature = "json")]
use serde::Serialize;

/// A context extension to read/write body more simply.
#[async_trait(?Send)]
pub trait PowerBody: Content {
    /// read request body as Vec<u8>.
    async fn body_bytes(&mut self) -> Result<Bytes>;

    /// read request body as "application/json".
    #[cfg(feature = "json")]
    async fn read_json<B: DeserializeOwned>(&mut self) -> Result<B>;

    /// read request body as "application/x-www-form-urlencoded".
    #[cfg(feature = "urlencoded")]
    async fn read_form<B: DeserializeOwned>(&mut self) -> Result<B>;

    /// write object to response body as "application/json; charset=utf-8"
    #[cfg(feature = "json")]
    fn write_json<B: Serialize>(&mut self, data: &B) -> Result;

    /// write object to response body as "text/html; charset=utf-8"
    #[cfg(feature = "template")]
    fn render<B: Template>(&mut self, data: &B) -> Result;

    /// write object to response body as "text/plain; charset=utf-8"
    fn write_text<S: ToString>(&mut self, string: S) -> Result;

    /// write object to response body as "application/octet-stream"
    fn write_octet<B: 'static + AsyncRead + Unpin + Sync + Send>(
        &mut self,
        reader: B,
    ) -> Result;

    /// write object to response body as extension name of file
    #[cfg(feature = "file")]
    async fn write_file<P: 'static + AsRef<Path>>(
        &mut self,
        path: P,
        typ: DispositionType,
    ) -> Result;
}

#[async_trait(?Send)]
impl<S: State> PowerBody for Context<S> {
    async fn body_bytes(&mut self) -> Result<Bytes> {
        let mut bytes = BytesMut::new();
        let mut stream = self.req_mut().stream();
        while let Some(item) = stream.next().await {
            bytes.extend(item?)
        }
        Ok(bytes.freeze())
    }

    #[cfg(feature = "json")]
    async fn read_json<B: DeserializeOwned>(&mut self) -> Result<B> {
        let content_type = self.content_type()?;
        content_type.expect(mime::APPLICATION_JSON)?;
        let data = self.body_bytes().await?;
        match content_type.charset() {
            None | Some(mime::UTF_8) => json::from_bytes(&data),
            Some(charset) => json::from_str(&decode::decode(&data, charset.as_str())?),
        }
    }

    #[cfg(feature = "urlencoded")]
    async fn read_form<B: DeserializeOwned>(&mut self) -> Result<B> {
        self.content_type()?
            .expect(mime::APPLICATION_WWW_FORM_URLENCODED)?;
        urlencoded::from_bytes(&self.body_bytes().await?)
    }

    #[cfg(feature = "json")]
    fn write_json<B: Serialize>(&mut self, data: &B) -> Result {
        self.resp_mut().write(json::to_bytes(data)?);
        let content_type: ContentType = "application/json; charset=utf-8".parse()?;
        self.resp_mut()
            .headers
            .insert(http::header::CONTENT_TYPE, content_type.to_value()?);
        Ok(())
    }

    #[cfg(feature = "template")]
    fn render<B: Template>(&mut self, data: &B) -> Result {
        self.resp_mut()
            .write(data.render().map_err(help::bug_report)?);
        let content_type: ContentType = "text/html; charset=utf-8".parse()?;
        self.resp_mut()
            .headers
            .insert(http::header::CONTENT_TYPE, content_type.to_value()?);
        Ok(())
    }

    fn write_text<Str: ToString>(&mut self, string: Str) -> Result {
        self.resp_mut().write(string.to_string());
        let content_type: ContentType = "text/plain; charset=utf-8".parse()?;
        self.resp_mut()
            .headers
            .insert(http::header::CONTENT_TYPE, content_type.to_value()?);
        Ok(())
    }

    fn write_octet<B: 'static + AsyncRead + Unpin + Sync + Send>(
        &mut self,
        reader: B,
    ) -> Result {
        self.resp_mut().write_reader(reader);
        let content_type: ContentType = "application/octet-stream".parse()?;
        self.resp_mut()
            .headers
            .insert(http::header::CONTENT_TYPE, content_type.to_value()?);
        Ok(())
    }

    #[cfg(feature = "file")]
    async fn write_file<P: 'static + AsRef<Path>>(
        &mut self,
        path: P,
        typ: DispositionType,
    ) -> Result {
        write_file(self, path, typ).await
    }
}

#[cfg(test)]
mod tests {
    use super::PowerBody;
    use askama::Template;
    use async_std::fs::File;
    use async_std::task::spawn;
    use encoding::EncoderTrap;
    use futures::io::BufReader;
    use http::header::CONTENT_TYPE;
    use http::StatusCode;
    use roa_core::http;
    use roa_core::App;
    use roa_tcp::Listener;
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Serialize, Deserialize, Hash, Eq, PartialEq, Clone, Template)]
    #[template(path = "user.html")]
    struct User {
        id: u64,
        name: String,
    }

    #[tokio::test]
    async fn read_json() -> Result<(), Box<dyn std::error::Error>> {
        // miss key
        let (addr, server) = App::new(())
            .end(move |mut ctx| async move {
                let user: User = ctx.read_json().await?;
                assert_eq!(
                    User {
                        id: 0,
                        name: "Hexilee".to_string()
                    },
                    user
                );
                Ok(())
            })
            .run()?;
        spawn(server);
        let client = reqwest::Client::new();

        let data = User {
            id: 0,
            name: "Hexilee".to_string(),
        };
        // err mime type
        let resp = client
            .get(&format!("http://{}", addr))
            .header(CONTENT_TYPE, "text/plain/html")
            .send()
            .await?;
        assert_eq!(StatusCode::BAD_REQUEST, resp.status());
        assert!(resp
            .text()
            .await?
            .ends_with("Content-Type value is invalid"));

        // json
        let resp = client
            .get(&format!("http://{}", addr))
            .json(&data)
            .send()
            .await?;
        assert_eq!(StatusCode::OK, resp.status());

        // unmatched Content-Type
        let resp = client
            .get(&format!("http://{}", addr))
            .body(serde_json::to_vec(&data)?)
            .header(CONTENT_TYPE, "text/xml")
            .send()
            .await?;
        assert_eq!(StatusCode::BAD_REQUEST, resp.status());
        assert_eq!(
            "content type unmatched. application/json != text/xml",
            resp.text().await?
        );

        // json; encoding
        let resp = client
            .get(&format!("http://{}", addr))
            .body(
                encoding::label::encoding_from_whatwg_label("gbk")
                    .unwrap()
                    .encode(&serde_json::to_string(&data)?, EncoderTrap::Strict)
                    .unwrap(),
            )
            .header(CONTENT_TYPE, "application/json; charset=gbk")
            .send()
            .await?;
        assert_eq!(StatusCode::OK, resp.status());
        Ok(())
    }

    #[tokio::test]
    async fn read_form() -> Result<(), Box<dyn std::error::Error>> {
        // miss key
        let (addr, server) = App::new(())
            .end(move |mut ctx| async move {
                let user: User = ctx.read_form().await?;
                assert_eq!(
                    User {
                        id: 0,
                        name: "Hexilee".to_string()
                    },
                    user
                );
                Ok(())
            })
            .run()?;
        spawn(server);
        let client = reqwest::Client::new();

        let data = User {
            id: 0,
            name: "Hexilee".to_string(),
        };
        // err mime type
        let resp = client
            .get(&format!("http://{}", addr))
            .header(CONTENT_TYPE, "text/plain/html")
            .send()
            .await?;
        assert_eq!(StatusCode::BAD_REQUEST, resp.status());
        assert!(resp
            .text()
            .await?
            .ends_with("Content-Type value is invalid"));

        // x-www-form-urlencoded
        let resp = client
            .get(&format!("http://{}", addr))
            .form(&data)
            .send()
            .await?;
        assert_eq!(StatusCode::OK, resp.status());

        // unmatched Content-Type
        let resp = client
            .get(&format!("http://{}", addr))
            .body(serde_json::to_vec(&data)?)
            .header(CONTENT_TYPE, "text/xml")
            .send()
            .await?;
        assert_eq!(StatusCode::BAD_REQUEST, resp.status());
        assert_eq!(
            "content type unmatched. application/x-www-form-urlencoded != text/xml",
            resp.text().await?
        );

        Ok(())
    }

    #[tokio::test]
    async fn render() -> Result<(), Box<dyn std::error::Error>> {
        // miss key
        let (addr, server) = App::new(())
            .end(move |mut ctx| async move {
                let user = User {
                    id: 0,
                    name: "Hexilee".to_string(),
                };
                ctx.render(&user)
            })
            .run()?;
        spawn(server);
        let resp = reqwest::get(&format!("http://{}", addr)).await?;
        assert_eq!(StatusCode::OK, resp.status());
        assert_eq!("text/html; charset=utf-8", resp.headers()[CONTENT_TYPE]);
        Ok(())
    }

    #[tokio::test]
    async fn write_text() -> Result<(), Box<dyn std::error::Error>> {
        // miss key
        let (addr, server) = App::new(())
            .end(move |mut ctx| async move { ctx.write_text("Hello, World!") })
            .run()?;
        spawn(server);
        let resp = reqwest::get(&format!("http://{}", addr)).await?;
        assert_eq!(StatusCode::OK, resp.status());
        assert_eq!("text/plain; charset=utf-8", resp.headers()[CONTENT_TYPE]);
        assert_eq!("Hello, World!", resp.text().await?);
        Ok(())
    }

    #[tokio::test]
    async fn write_octet() -> Result<(), Box<dyn std::error::Error>> {
        // miss key
        let (addr, server) = App::new(())
            .end(move |mut ctx| async move {
                ctx.write_octet(BufReader::new(
                    File::open("../assets/author.txt").await?,
                ))
            })
            .run()?;
        spawn(server);
        let resp = reqwest::get(&format!("http://{}", addr)).await?;
        assert_eq!(StatusCode::OK, resp.status());
        assert_eq!(
            mime::APPLICATION_OCTET_STREAM.as_ref(),
            resp.headers()[CONTENT_TYPE]
        );
        assert_eq!("Hexilee", resp.text().await?);
        Ok(())
    }
}