2018-07-04 17:01:27 +02:00
|
|
|
use bytes::BytesMut;
|
2018-04-14 01:02:01 +02:00
|
|
|
use futures::{Future, Poll, Stream};
|
2017-12-21 05:30:54 +01:00
|
|
|
use http::header::CONTENT_LENGTH;
|
|
|
|
|
2018-03-10 19:27:29 +01:00
|
|
|
use mime;
|
2017-12-21 05:30:54 +01:00
|
|
|
use serde::de::DeserializeOwned;
|
2018-04-14 01:02:01 +02:00
|
|
|
use serde_json;
|
2017-12-21 02:51:28 +01:00
|
|
|
|
2018-12-06 23:32:52 +01:00
|
|
|
use crate::error::JsonPayloadError;
|
|
|
|
use crate::httpmessage::HttpMessage;
|
2017-12-21 02:51:28 +01:00
|
|
|
|
2017-12-21 05:30:54 +01:00
|
|
|
/// Request payload json parser that resolves to a deserialized `T` value.
|
|
|
|
///
|
|
|
|
/// Returns error:
|
|
|
|
///
|
|
|
|
/// * content type is not `application/json`
|
|
|
|
/// * content length is greater than 256k
|
|
|
|
///
|
2018-02-28 00:03:28 +01:00
|
|
|
/// # Server example
|
|
|
|
///
|
2018-10-05 06:14:18 +02:00
|
|
|
/// ```rust,ignore
|
2017-12-21 05:30:54 +01:00
|
|
|
/// # extern crate actix_web;
|
|
|
|
/// # extern crate futures;
|
|
|
|
/// # #[macro_use] extern crate serde_derive;
|
2018-10-05 20:04:59 +02:00
|
|
|
/// use actix_web::{AsyncResponder, Error, HttpMessage, HttpRequest, Response};
|
2017-12-21 05:30:54 +01:00
|
|
|
/// use futures::future::Future;
|
|
|
|
///
|
|
|
|
/// #[derive(Deserialize, Debug)]
|
|
|
|
/// struct MyObj {
|
|
|
|
/// name: String,
|
|
|
|
/// }
|
|
|
|
///
|
2018-10-05 20:04:59 +02:00
|
|
|
/// fn index(mut req: HttpRequest) -> Box<Future<Item = Response, Error = Error>> {
|
2017-12-21 05:30:54 +01:00
|
|
|
/// req.json() // <- get JsonBody future
|
|
|
|
/// .from_err()
|
|
|
|
/// .and_then(|val: MyObj| { // <- deserialized value
|
|
|
|
/// println!("==== BODY ==== {:?}", val);
|
2018-10-05 20:04:59 +02:00
|
|
|
/// Ok(Response::Ok().into())
|
2017-12-21 05:30:54 +01:00
|
|
|
/// }).responder()
|
|
|
|
/// }
|
|
|
|
/// # fn main() {}
|
|
|
|
/// ```
|
2018-06-25 06:58:04 +02:00
|
|
|
pub struct JsonBody<T: HttpMessage, U: DeserializeOwned> {
|
2017-12-21 05:30:54 +01:00
|
|
|
limit: usize,
|
2018-06-25 06:58:04 +02:00
|
|
|
length: Option<usize>,
|
|
|
|
stream: Option<T::Stream>,
|
|
|
|
err: Option<JsonPayloadError>,
|
2018-04-14 01:02:01 +02:00
|
|
|
fut: Option<Box<Future<Item = U, Error = JsonPayloadError>>>,
|
2017-12-21 05:30:54 +01:00
|
|
|
}
|
|
|
|
|
2018-06-25 06:58:04 +02:00
|
|
|
impl<T: HttpMessage, U: DeserializeOwned> JsonBody<T, U> {
|
2017-12-21 05:56:17 +01:00
|
|
|
/// Create `JsonBody` for request.
|
2018-06-25 06:58:04 +02:00
|
|
|
pub fn new(req: &T) -> Self {
|
|
|
|
// check content-type
|
|
|
|
let json = if let Ok(Some(mime)) = req.mime_type() {
|
|
|
|
mime.subtype() == mime::JSON || mime.suffix() == Some(mime::JSON)
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
};
|
|
|
|
if !json {
|
|
|
|
return JsonBody {
|
|
|
|
limit: 262_144,
|
|
|
|
length: None,
|
|
|
|
stream: None,
|
|
|
|
fut: None,
|
|
|
|
err: Some(JsonPayloadError::ContentType),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut len = None;
|
|
|
|
if let Some(l) = req.headers().get(CONTENT_LENGTH) {
|
|
|
|
if let Ok(s) = l.to_str() {
|
|
|
|
if let Ok(l) = s.parse::<usize>() {
|
|
|
|
len = Some(l)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-14 01:02:01 +02:00
|
|
|
JsonBody {
|
2017-12-21 05:30:54 +01:00
|
|
|
limit: 262_144,
|
2018-06-25 06:58:04 +02:00
|
|
|
length: len,
|
|
|
|
stream: Some(req.payload()),
|
2017-12-21 05:30:54 +01:00
|
|
|
fut: None,
|
2018-06-25 06:58:04 +02:00
|
|
|
err: None,
|
2017-12-21 05:30:54 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Change max size of payload. By default max size is 256Kb
|
|
|
|
pub fn limit(mut self, limit: usize) -> Self {
|
|
|
|
self.limit = limit;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-06-25 06:58:04 +02:00
|
|
|
impl<T: HttpMessage + 'static, U: DeserializeOwned + 'static> Future for JsonBody<T, U> {
|
2018-02-28 00:03:28 +01:00
|
|
|
type Item = U;
|
2017-12-21 05:30:54 +01:00
|
|
|
type Error = JsonPayloadError;
|
|
|
|
|
2018-02-28 00:03:28 +01:00
|
|
|
fn poll(&mut self) -> Poll<U, JsonPayloadError> {
|
2018-06-25 06:58:04 +02:00
|
|
|
if let Some(ref mut fut) = self.fut {
|
|
|
|
return fut.poll();
|
|
|
|
}
|
2018-03-10 19:27:29 +01:00
|
|
|
|
2018-06-25 06:58:04 +02:00
|
|
|
if let Some(err) = self.err.take() {
|
|
|
|
return Err(err);
|
|
|
|
}
|
2017-12-21 05:30:54 +01:00
|
|
|
|
2018-06-25 06:58:04 +02:00
|
|
|
let limit = self.limit;
|
|
|
|
if let Some(len) = self.length.take() {
|
|
|
|
if len > limit {
|
|
|
|
return Err(JsonPayloadError::Overflow);
|
|
|
|
}
|
2017-12-21 05:30:54 +01:00
|
|
|
}
|
|
|
|
|
2018-06-25 06:58:04 +02:00
|
|
|
let fut = self
|
|
|
|
.stream
|
|
|
|
.take()
|
2018-04-29 18:09:08 +02:00
|
|
|
.expect("JsonBody could not be used second time")
|
2018-06-25 06:58:04 +02:00
|
|
|
.from_err()
|
2018-07-15 20:40:22 +02:00
|
|
|
.fold(BytesMut::with_capacity(8192), move |mut body, chunk| {
|
2018-06-25 06:58:04 +02:00
|
|
|
if (body.len() + chunk.len()) > limit {
|
|
|
|
Err(JsonPayloadError::Overflow)
|
|
|
|
} else {
|
|
|
|
body.extend_from_slice(&chunk);
|
|
|
|
Ok(body)
|
|
|
|
}
|
2018-12-06 23:32:52 +01:00
|
|
|
})
|
|
|
|
.and_then(|body| Ok(serde_json::from_slice::<U>(&body)?));
|
2018-06-25 06:58:04 +02:00
|
|
|
self.fut = Some(Box::new(fut));
|
|
|
|
self.poll()
|
2017-12-21 05:30:54 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-21 02:51:28 +01:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2017-12-21 05:30:54 +01:00
|
|
|
use bytes::Bytes;
|
|
|
|
use futures::Async;
|
2018-04-14 01:02:01 +02:00
|
|
|
use http::header;
|
2018-12-07 00:03:01 +01:00
|
|
|
use serde_derive::{Deserialize, Serialize};
|
2017-12-21 05:30:54 +01:00
|
|
|
|
2019-01-27 19:59:07 +01:00
|
|
|
use super::*;
|
2018-12-07 00:03:01 +01:00
|
|
|
use crate::test::TestRequest;
|
2018-03-27 08:10:31 +02:00
|
|
|
|
2017-12-21 05:30:54 +01:00
|
|
|
impl PartialEq for JsonPayloadError {
|
|
|
|
fn eq(&self, other: &JsonPayloadError) -> bool {
|
|
|
|
match *self {
|
|
|
|
JsonPayloadError::Overflow => match *other {
|
|
|
|
JsonPayloadError::Overflow => true,
|
|
|
|
_ => false,
|
|
|
|
},
|
|
|
|
JsonPayloadError::ContentType => match *other {
|
|
|
|
JsonPayloadError::ContentType => true,
|
|
|
|
_ => false,
|
|
|
|
},
|
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-12-21 02:51:28 +01:00
|
|
|
|
2017-12-21 05:30:54 +01:00
|
|
|
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
|
|
|
struct MyObject {
|
|
|
|
name: String,
|
2017-12-21 02:51:28 +01:00
|
|
|
}
|
|
|
|
|
2017-12-21 05:30:54 +01:00
|
|
|
#[test]
|
|
|
|
fn test_json_body() {
|
2018-06-25 06:58:04 +02:00
|
|
|
let req = TestRequest::default().finish();
|
2017-12-21 05:30:54 +01:00
|
|
|
let mut json = req.json::<MyObject>();
|
2018-05-17 21:20:20 +02:00
|
|
|
assert_eq!(json.poll().err().unwrap(), JsonPayloadError::ContentType);
|
2017-12-21 05:30:54 +01:00
|
|
|
|
2018-06-25 06:58:04 +02:00
|
|
|
let req = TestRequest::default()
|
|
|
|
.header(
|
|
|
|
header::CONTENT_TYPE,
|
|
|
|
header::HeaderValue::from_static("application/text"),
|
2018-12-06 23:32:52 +01:00
|
|
|
)
|
|
|
|
.finish();
|
2018-03-10 19:42:46 +01:00
|
|
|
let mut json = req.json::<MyObject>();
|
2018-05-17 21:20:20 +02:00
|
|
|
assert_eq!(json.poll().err().unwrap(), JsonPayloadError::ContentType);
|
2017-12-21 05:30:54 +01:00
|
|
|
|
2018-06-25 06:58:04 +02:00
|
|
|
let req = TestRequest::default()
|
|
|
|
.header(
|
|
|
|
header::CONTENT_TYPE,
|
|
|
|
header::HeaderValue::from_static("application/json"),
|
2018-12-06 23:32:52 +01:00
|
|
|
)
|
|
|
|
.header(
|
2018-06-25 06:58:04 +02:00
|
|
|
header::CONTENT_LENGTH,
|
|
|
|
header::HeaderValue::from_static("10000"),
|
2018-12-06 23:32:52 +01:00
|
|
|
)
|
|
|
|
.finish();
|
2018-02-26 03:55:07 +01:00
|
|
|
let mut json = req.json::<MyObject>().limit(100);
|
2017-12-21 05:30:54 +01:00
|
|
|
assert_eq!(json.poll().err().unwrap(), JsonPayloadError::Overflow);
|
|
|
|
|
2018-06-25 06:58:04 +02:00
|
|
|
let req = TestRequest::default()
|
|
|
|
.header(
|
|
|
|
header::CONTENT_TYPE,
|
|
|
|
header::HeaderValue::from_static("application/json"),
|
2018-12-06 23:32:52 +01:00
|
|
|
)
|
|
|
|
.header(
|
2018-06-25 06:58:04 +02:00
|
|
|
header::CONTENT_LENGTH,
|
|
|
|
header::HeaderValue::from_static("16"),
|
2018-12-06 23:32:52 +01:00
|
|
|
)
|
|
|
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
2018-06-25 06:58:04 +02:00
|
|
|
.finish();
|
|
|
|
|
2017-12-21 05:30:54 +01:00
|
|
|
let mut json = req.json::<MyObject>();
|
2018-04-14 01:02:01 +02:00
|
|
|
assert_eq!(
|
|
|
|
json.poll().ok().unwrap(),
|
|
|
|
Async::Ready(MyObject {
|
|
|
|
name: "test".to_owned()
|
|
|
|
})
|
|
|
|
);
|
2018-03-27 08:10:31 +02:00
|
|
|
}
|
2017-12-21 02:51:28 +01:00
|
|
|
}
|