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;

///! parses the request body as json
///! if the content-type header is set.
///! note that if there are any errors in parsing the json
///! it will return an error response.
#[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 {
		// this unwrap is safe. check request.rs: line 50
		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());
			}
		};

		// assert that the chunk length is > 0
		// otherwise bad request.
		if chunk.len() == 0 {
			let error = json!({ "error": "Empty request body" });
			return Err((400, error).into());
		}

		req.set(chunk);
	}

	Ok(req)
}