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
use futures::{Future, Stream};
use futures::prelude::{async_block, await};
use core::{Request, Response};
use proto::MiddleWare;
use impl_service::middleware;
use hyper::header::ContentType;
#[middleware(Request)]
pub fn body_parser(mut req: Request) {
let mut isJson = false;
{
if let Some(ct) = req.headers.get::<ContentType>() {
isJson = *ct == ContentType::json();
}
}
if isJson {
let body = req.body.take().unwrap();
let chunk = match await!(body.concat2()) {
Ok(chunk) => chunk,
Err(_) => {
let error = json!({
"error": "Could not read request payload"
});
return Err((400, error).into());
}
};
if chunk.len() == 0 {
let error = json!({ "error": "Empty request body" });
return Err((400, error).into());
}
req.set(chunk);
}
Ok(req)
}