2018-02-28 00:03:28 +01:00
|
|
|
use bytes::{Bytes, BytesMut};
|
2017-12-21 05:30:54 +01:00
|
|
|
use futures::{Poll, Future, Stream};
|
|
|
|
use http::header::CONTENT_LENGTH;
|
|
|
|
|
2017-12-21 02:51:28 +01:00
|
|
|
use serde_json;
|
|
|
|
use serde::Serialize;
|
2017-12-21 05:30:54 +01:00
|
|
|
use serde::de::DeserializeOwned;
|
2017-12-21 02:51:28 +01:00
|
|
|
|
2018-02-28 00:03:28 +01:00
|
|
|
use error::{Error, JsonPayloadError, PayloadError};
|
2017-12-21 02:51:28 +01:00
|
|
|
use handler::Responder;
|
2018-02-28 00:03:28 +01:00
|
|
|
use httpmessage::HttpMessage;
|
2017-12-21 02:51:28 +01:00
|
|
|
use httprequest::HttpRequest;
|
|
|
|
use httpresponse::HttpResponse;
|
|
|
|
|
|
|
|
/// Json response helper
|
|
|
|
///
|
|
|
|
/// The `Json` type allows you to respond with well-formed JSON data: simply return a value of
|
|
|
|
/// type Json<T> where T is the type of a structure to serialize into *JSON*. The
|
|
|
|
/// type `T` must implement the `Serialize` trait from *serde*.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # extern crate actix_web;
|
|
|
|
/// # #[macro_use] extern crate serde_derive;
|
|
|
|
/// # use actix_web::*;
|
|
|
|
/// #
|
|
|
|
/// #[derive(Serialize)]
|
|
|
|
/// struct MyObj {
|
|
|
|
/// name: String,
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn index(req: HttpRequest) -> Result<Json<MyObj>> {
|
|
|
|
/// Ok(Json(MyObj{name: req.match_info().query("name")?}))
|
|
|
|
/// }
|
|
|
|
/// # fn main() {}
|
|
|
|
/// ```
|
|
|
|
pub struct Json<T: Serialize> (pub T);
|
|
|
|
|
|
|
|
impl<T: Serialize> Responder for Json<T> {
|
|
|
|
type Item = HttpResponse;
|
|
|
|
type Error = Error;
|
|
|
|
|
|
|
|
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, Error> {
|
|
|
|
let body = serde_json::to_string(&self.0)?;
|
|
|
|
|
|
|
|
Ok(HttpResponse::Ok()
|
|
|
|
.content_type("application/json")
|
|
|
|
.body(body)?)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
///
|
2017-12-21 05:30:54 +01:00
|
|
|
/// ```rust
|
|
|
|
/// # extern crate actix_web;
|
|
|
|
/// # extern crate futures;
|
|
|
|
/// # #[macro_use] extern crate serde_derive;
|
|
|
|
/// use actix_web::*;
|
|
|
|
/// use futures::future::Future;
|
|
|
|
///
|
|
|
|
/// #[derive(Deserialize, Debug)]
|
|
|
|
/// struct MyObj {
|
|
|
|
/// name: String,
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn index(mut req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
|
|
|
|
/// req.json() // <- get JsonBody future
|
|
|
|
/// .from_err()
|
|
|
|
/// .and_then(|val: MyObj| { // <- deserialized value
|
|
|
|
/// println!("==== BODY ==== {:?}", val);
|
2018-03-02 04:12:59 +01:00
|
|
|
/// Ok(httpcodes::HttpOk.into())
|
2017-12-21 05:30:54 +01:00
|
|
|
/// }).responder()
|
|
|
|
/// }
|
|
|
|
/// # fn main() {}
|
|
|
|
/// ```
|
2018-02-28 00:03:28 +01:00
|
|
|
pub struct JsonBody<T, U: DeserializeOwned>{
|
2017-12-21 05:30:54 +01:00
|
|
|
limit: usize,
|
|
|
|
ct: &'static str,
|
2018-02-28 00:03:28 +01:00
|
|
|
req: Option<T>,
|
|
|
|
fut: Option<Box<Future<Item=U, Error=JsonPayloadError>>>,
|
2017-12-21 05:30:54 +01:00
|
|
|
}
|
|
|
|
|
2018-02-28 00:03:28 +01:00
|
|
|
impl<T, U: DeserializeOwned> JsonBody<T, U> {
|
2017-12-21 05:30:54 +01:00
|
|
|
|
2017-12-21 05:56:17 +01:00
|
|
|
/// Create `JsonBody` for request.
|
2018-02-28 00:03:28 +01:00
|
|
|
pub fn new(req: T) -> Self {
|
2017-12-21 05:30:54 +01:00
|
|
|
JsonBody{
|
|
|
|
limit: 262_144,
|
2018-02-25 18:34:26 +01:00
|
|
|
req: Some(req),
|
2017-12-21 05:30:54 +01:00
|
|
|
fut: None,
|
|
|
|
ct: "application/json",
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Change max size of payload. By default max size is 256Kb
|
|
|
|
pub fn limit(mut self, limit: usize) -> Self {
|
|
|
|
self.limit = limit;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set allowed content type.
|
|
|
|
///
|
|
|
|
/// By default *application/json* content type is used. Set content type
|
|
|
|
/// to empty string if you want to disable content type check.
|
|
|
|
pub fn content_type(mut self, ct: &'static str) -> Self {
|
|
|
|
self.ct = ct;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-28 00:03:28 +01:00
|
|
|
impl<T, U: DeserializeOwned + 'static> Future for JsonBody<T, U>
|
|
|
|
where T: HttpMessage + Stream<Item=Bytes, Error=PayloadError> + 'static
|
|
|
|
{
|
|
|
|
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-01-03 18:23:58 +01:00
|
|
|
if let Some(req) = self.req.take() {
|
2017-12-21 05:30:54 +01:00
|
|
|
if let Some(len) = req.headers().get(CONTENT_LENGTH) {
|
|
|
|
if let Ok(s) = len.to_str() {
|
|
|
|
if let Ok(len) = s.parse::<usize>() {
|
|
|
|
if len > self.limit {
|
|
|
|
return Err(JsonPayloadError::Overflow);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return Err(JsonPayloadError::Overflow);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// check content-type
|
|
|
|
if !self.ct.is_empty() && req.content_type() != self.ct {
|
|
|
|
return Err(JsonPayloadError::ContentType)
|
|
|
|
}
|
|
|
|
|
|
|
|
let limit = self.limit;
|
2018-02-25 09:21:45 +01:00
|
|
|
let fut = req.from_err()
|
2017-12-21 05:30:54 +01:00
|
|
|
.fold(BytesMut::new(), move |mut body, chunk| {
|
|
|
|
if (body.len() + chunk.len()) > limit {
|
|
|
|
Err(JsonPayloadError::Overflow)
|
|
|
|
} else {
|
|
|
|
body.extend_from_slice(&chunk);
|
|
|
|
Ok(body)
|
|
|
|
}
|
|
|
|
})
|
2018-02-28 00:03:28 +01:00
|
|
|
.and_then(|body| Ok(serde_json::from_slice::<U>(&body)?));
|
2017-12-21 05:30:54 +01:00
|
|
|
self.fut = Some(Box::new(fut));
|
|
|
|
}
|
|
|
|
|
|
|
|
self.fut.as_mut().expect("JsonBody could not be used second time").poll()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-21 02:51:28 +01:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
2017-12-21 05:30:54 +01:00
|
|
|
use bytes::Bytes;
|
|
|
|
use http::header;
|
|
|
|
use futures::Async;
|
|
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_json() {
|
2017-12-21 05:30:54 +01:00
|
|
|
let json = Json(MyObject{name: "test".to_owned()});
|
2017-12-21 02:51:28 +01:00
|
|
|
let resp = json.respond_to(HttpRequest::default()).unwrap();
|
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(), "application/json");
|
|
|
|
}
|
|
|
|
|
2017-12-21 05:30:54 +01:00
|
|
|
#[test]
|
|
|
|
fn test_json_body() {
|
2018-02-26 03:55:07 +01:00
|
|
|
let req = HttpRequest::default();
|
2017-12-21 05:30:54 +01:00
|
|
|
let mut json = req.json::<MyObject>();
|
|
|
|
assert_eq!(json.poll().err().unwrap(), JsonPayloadError::ContentType);
|
|
|
|
|
2018-02-26 03:55:07 +01:00
|
|
|
let mut req = HttpRequest::default();
|
2017-12-21 05:30:54 +01:00
|
|
|
req.headers_mut().insert(header::CONTENT_TYPE,
|
|
|
|
header::HeaderValue::from_static("application/json"));
|
2018-02-26 03:55:07 +01:00
|
|
|
let mut json = req.json::<MyObject>().content_type("text/json");
|
2017-12-21 05:30:54 +01:00
|
|
|
assert_eq!(json.poll().err().unwrap(), JsonPayloadError::ContentType);
|
|
|
|
|
2018-02-26 03:55:07 +01:00
|
|
|
let mut req = HttpRequest::default();
|
2017-12-21 05:30:54 +01:00
|
|
|
req.headers_mut().insert(header::CONTENT_TYPE,
|
|
|
|
header::HeaderValue::from_static("application/json"));
|
|
|
|
req.headers_mut().insert(header::CONTENT_LENGTH,
|
|
|
|
header::HeaderValue::from_static("10000"));
|
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-02-26 03:55:07 +01:00
|
|
|
let mut req = HttpRequest::default();
|
|
|
|
req.headers_mut().insert(header::CONTENT_TYPE,
|
|
|
|
header::HeaderValue::from_static("application/json"));
|
2017-12-21 05:30:54 +01:00
|
|
|
req.headers_mut().insert(header::CONTENT_LENGTH,
|
|
|
|
header::HeaderValue::from_static("16"));
|
|
|
|
req.payload_mut().unread_data(Bytes::from_static(b"{\"name\": \"test\"}"));
|
|
|
|
let mut json = req.json::<MyObject>();
|
|
|
|
assert_eq!(json.poll().ok().unwrap(), Async::Ready(MyObject{name: "test".to_owned()}));
|
|
|
|
}
|
2017-12-21 02:51:28 +01:00
|
|
|
}
|