2018-02-28 00:03:28 +01:00
|
|
|
use bytes::{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-04-14 01:02:01 +02:00
|
|
|
use std::fmt;
|
|
|
|
use std::ops::{Deref, DerefMut};
|
2017-12-21 05:30:54 +01:00
|
|
|
|
2018-03-10 19:27:29 +01:00
|
|
|
use mime;
|
2017-12-21 02:51:28 +01:00
|
|
|
use serde::Serialize;
|
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-02-28 00:03:28 +01:00
|
|
|
use error::{Error, JsonPayloadError, PayloadError};
|
2018-04-14 01:02:01 +02:00
|
|
|
use handler::{FromRequest, Responder};
|
2018-04-04 02:37:17 +02:00
|
|
|
use http::StatusCode;
|
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;
|
|
|
|
|
2018-03-29 19:44:26 +02:00
|
|
|
/// Json helper
|
2017-12-21 02:51:28 +01:00
|
|
|
///
|
2018-04-14 01:02:01 +02:00
|
|
|
/// Json can be used for two different purpose. First is for json response
|
|
|
|
/// generation and second is for extracting typed information from request's
|
|
|
|
/// payload.
|
|
|
|
///
|
|
|
|
/// To extract typed information from request's body, the type `T` must
|
|
|
|
/// implement the `Deserialize` trait from *serde*.
|
|
|
|
///
|
|
|
|
/// [**JsonConfig**](dev/struct.JsonConfig.html) allows to configure extraction
|
|
|
|
/// process.
|
|
|
|
///
|
|
|
|
/// ## Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # extern crate actix_web;
|
|
|
|
/// #[macro_use] extern crate serde_derive;
|
|
|
|
/// use actix_web::{App, Json, Result, http};
|
|
|
|
///
|
|
|
|
/// #[derive(Deserialize)]
|
|
|
|
/// struct Info {
|
|
|
|
/// username: String,
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// /// deserialize `Info` from request's body
|
|
|
|
/// fn index(info: Json<Info>) -> Result<String> {
|
|
|
|
/// Ok(format!("Welcome {}!", info.username))
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let app = App::new().resource(
|
|
|
|
/// "/index.html",
|
|
|
|
/// |r| r.method(http::Method::POST).with(index)); // <- use `with` extractor
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// 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() {}
|
|
|
|
/// ```
|
2018-04-03 01:19:18 +02:00
|
|
|
pub struct Json<T>(pub T);
|
|
|
|
|
2018-04-13 00:55:15 +02:00
|
|
|
impl<T> Json<T> {
|
|
|
|
/// Deconstruct to an inner value
|
|
|
|
pub fn into_inner(self) -> T {
|
|
|
|
self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-03 01:19:18 +02:00
|
|
|
impl<T> Deref for Json<T> {
|
|
|
|
type Target = T;
|
|
|
|
|
|
|
|
fn deref(&self) -> &T {
|
|
|
|
&self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> DerefMut for Json<T> {
|
|
|
|
fn deref_mut(&mut self) -> &mut T {
|
|
|
|
&mut self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-14 01:02:01 +02:00
|
|
|
impl<T> fmt::Debug for Json<T>
|
|
|
|
where
|
|
|
|
T: fmt::Debug,
|
|
|
|
{
|
2018-04-03 01:19:18 +02:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
write!(f, "Json: {:?}", self.0)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-14 01:02:01 +02:00
|
|
|
impl<T> fmt::Display for Json<T>
|
|
|
|
where
|
|
|
|
T: fmt::Display,
|
|
|
|
{
|
2018-04-03 01:19:18 +02:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
fmt::Display::fmt(&self.0, f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: Serialize> Responder for Json<T> {
|
|
|
|
type Item = HttpResponse;
|
|
|
|
type Error = Error;
|
|
|
|
|
2018-04-04 02:37:17 +02:00
|
|
|
fn respond_to(self, req: HttpRequest) -> Result<HttpResponse, Error> {
|
2018-04-03 01:19:18 +02:00
|
|
|
let body = serde_json::to_string(&self.0)?;
|
|
|
|
|
2018-04-04 02:37:17 +02:00
|
|
|
Ok(req.build_response(StatusCode::OK)
|
2018-04-14 01:02:01 +02:00
|
|
|
.content_type("application/json")
|
|
|
|
.body(body))
|
2018-04-03 01:19:18 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-29 22:12:28 +02:00
|
|
|
impl<T, S> FromRequest<S> for Json<T>
|
2018-04-14 01:02:01 +02:00
|
|
|
where
|
|
|
|
T: DeserializeOwned + 'static,
|
|
|
|
S: 'static,
|
2018-03-27 08:10:31 +02:00
|
|
|
{
|
2018-04-04 07:06:18 +02:00
|
|
|
type Config = JsonConfig;
|
2018-04-14 01:02:01 +02:00
|
|
|
type Result = Box<Future<Item = Self, Error = Error>>;
|
2018-03-27 08:10:31 +02:00
|
|
|
|
|
|
|
#[inline]
|
2018-04-04 07:06:18 +02:00
|
|
|
fn from_request(req: &HttpRequest<S>, cfg: &Self::Config) -> Self::Result {
|
2018-03-27 08:10:31 +02:00
|
|
|
Box::new(
|
|
|
|
JsonBody::new(req.clone())
|
2018-04-04 07:06:18 +02:00
|
|
|
.limit(cfg.limit)
|
2018-03-27 08:10:31 +02:00
|
|
|
.from_err()
|
2018-04-14 01:02:01 +02:00
|
|
|
.map(Json),
|
|
|
|
)
|
2018-03-27 08:10:31 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-04 07:06:18 +02:00
|
|
|
/// Json extractor configuration
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # extern crate actix_web;
|
|
|
|
/// #[macro_use] extern crate serde_derive;
|
|
|
|
/// use actix_web::{App, Json, Result, http};
|
|
|
|
///
|
|
|
|
/// #[derive(Deserialize)]
|
|
|
|
/// struct Info {
|
|
|
|
/// username: String,
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// /// deserialize `Info` from request's body, max payload size is 4kb
|
|
|
|
/// fn index(info: Json<Info>) -> Result<String> {
|
|
|
|
/// Ok(format!("Welcome {}!", info.username))
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let app = App::new().resource(
|
|
|
|
/// "/index.html", |r| {
|
|
|
|
/// r.method(http::Method::POST)
|
|
|
|
/// .with(index)
|
|
|
|
/// .limit(4096);} // <- change json extractor configuration
|
|
|
|
/// );
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
pub struct JsonConfig {
|
|
|
|
limit: usize,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl JsonConfig {
|
|
|
|
/// Change max size of payload. By default max size is 256Kb
|
|
|
|
pub fn limit(&mut self, limit: usize) -> &mut Self {
|
|
|
|
self.limit = limit;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for JsonConfig {
|
|
|
|
fn default() -> Self {
|
2018-04-14 01:02:01 +02:00
|
|
|
JsonConfig { limit: 262_144 }
|
2018-04-04 07:06:18 +02: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
|
|
|
|
///
|
2017-12-21 05:30:54 +01:00
|
|
|
/// ```rust
|
|
|
|
/// # extern crate actix_web;
|
|
|
|
/// # extern crate futures;
|
|
|
|
/// # #[macro_use] extern crate serde_derive;
|
|
|
|
/// use futures::future::Future;
|
2018-03-31 09:16:55 +02:00
|
|
|
/// use actix_web::{AsyncResponder, HttpRequest, HttpResponse, HttpMessage, Error};
|
2017-12-21 05:30:54 +01:00
|
|
|
///
|
|
|
|
/// #[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-31 08:07:33 +02:00
|
|
|
/// Ok(HttpResponse::Ok().into())
|
2017-12-21 05:30:54 +01:00
|
|
|
/// }).responder()
|
|
|
|
/// }
|
|
|
|
/// # fn main() {}
|
|
|
|
/// ```
|
2018-04-14 01:02:01 +02:00
|
|
|
pub struct JsonBody<T, U: DeserializeOwned> {
|
2017-12-21 05:30:54 +01:00
|
|
|
limit: usize,
|
2018-02-28 00:03:28 +01:00
|
|
|
req: Option<T>,
|
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-02-28 00:03:28 +01:00
|
|
|
impl<T, U: DeserializeOwned> JsonBody<T, U> {
|
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 {
|
2018-04-14 01:02:01 +02:00
|
|
|
JsonBody {
|
2017-12-21 05:30:54 +01:00
|
|
|
limit: 262_144,
|
2018-02-25 18:34:26 +01:00
|
|
|
req: Some(req),
|
2017-12-21 05:30:54 +01:00
|
|
|
fut: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Change max size of payload. By default max size is 256Kb
|
|
|
|
pub fn limit(mut self, limit: usize) -> Self {
|
|
|
|
self.limit = limit;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-28 00:03:28 +01:00
|
|
|
impl<T, U: DeserializeOwned + 'static> Future for JsonBody<T, U>
|
2018-04-14 01:02:01 +02:00
|
|
|
where
|
|
|
|
T: HttpMessage + Stream<Item = Bytes, Error = PayloadError> + 'static,
|
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-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
|
2018-03-10 19:27:29 +01:00
|
|
|
|
|
|
|
let json = if let Ok(Some(mime)) = req.mime_type() {
|
|
|
|
mime.subtype() == mime::JSON || mime.suffix() == Some(mime::JSON)
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
};
|
|
|
|
if !json {
|
2018-04-14 01:02:01 +02:00
|
|
|
return Err(JsonPayloadError::ContentType);
|
2017-12-21 05:30:54 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
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));
|
|
|
|
}
|
|
|
|
|
2018-04-14 01:02:01 +02:00
|
|
|
self.fut
|
|
|
|
.as_mut()
|
|
|
|
.expect("JsonBody could not be used second time")
|
|
|
|
.poll()
|
2017-12-21 05:30:54 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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 futures::Async;
|
2018-04-14 01:02:01 +02:00
|
|
|
use http::header;
|
2017-12-21 05:30:54 +01:00
|
|
|
|
2018-03-27 08:10:31 +02:00
|
|
|
use handler::Handler;
|
2018-04-14 01:02:01 +02:00
|
|
|
use with::{ExtractorConfig, With};
|
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
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_json() {
|
2018-04-14 01:02:01 +02: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();
|
2018-04-14 01:02:01 +02:00
|
|
|
assert_eq!(
|
|
|
|
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
"application/json"
|
|
|
|
);
|
2017-12-21 02:51:28 +01:00
|
|
|
}
|
|
|
|
|
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>();
|
2018-04-14 01:02:01 +02:00
|
|
|
assert_eq!(
|
|
|
|
json.poll().err().unwrap(),
|
|
|
|
JsonPayloadError::ContentType
|
|
|
|
);
|
2017-12-21 05:30:54 +01:00
|
|
|
|
2018-02-26 03:55:07 +01:00
|
|
|
let mut req = HttpRequest::default();
|
2018-04-14 01:02:01 +02:00
|
|
|
req.headers_mut().insert(
|
|
|
|
header::CONTENT_TYPE,
|
|
|
|
header::HeaderValue::from_static("application/text"),
|
|
|
|
);
|
2018-03-10 19:42:46 +01:00
|
|
|
let mut json = req.json::<MyObject>();
|
2018-04-14 01:02:01 +02:00
|
|
|
assert_eq!(
|
|
|
|
json.poll().err().unwrap(),
|
|
|
|
JsonPayloadError::ContentType
|
|
|
|
);
|
2017-12-21 05:30:54 +01:00
|
|
|
|
2018-02-26 03:55:07 +01:00
|
|
|
let mut req = HttpRequest::default();
|
2018-04-14 01:02:01 +02: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();
|
2018-04-14 01:02:01 +02: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("16"),
|
|
|
|
);
|
|
|
|
req.payload_mut()
|
|
|
|
.unread_data(Bytes::from_static(b"{\"name\": \"test\"}"));
|
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
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_with_json() {
|
2018-04-04 07:06:18 +02:00
|
|
|
let mut cfg = ExtractorConfig::<_, Json<MyObject>>::default();
|
|
|
|
cfg.limit(4096);
|
2018-04-14 01:02:01 +02:00
|
|
|
let mut handler = With::new(|data: Json<MyObject>| data, cfg);
|
2018-03-27 08:10:31 +02:00
|
|
|
|
|
|
|
let req = HttpRequest::default();
|
2018-04-14 01:02:01 +02:00
|
|
|
let err = handler
|
|
|
|
.handle(req)
|
|
|
|
.as_response()
|
|
|
|
.unwrap()
|
|
|
|
.error()
|
|
|
|
.is_some();
|
2018-03-29 06:33:40 +02:00
|
|
|
assert!(err);
|
2018-03-27 08:10:31 +02:00
|
|
|
|
|
|
|
let mut req = HttpRequest::default();
|
2018-04-14 01:02:01 +02: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("16"),
|
|
|
|
);
|
|
|
|
req.payload_mut()
|
|
|
|
.unread_data(Bytes::from_static(b"{\"name\": \"test\"}"));
|
|
|
|
let ok = handler
|
|
|
|
.handle(req)
|
|
|
|
.as_response()
|
|
|
|
.unwrap()
|
|
|
|
.error()
|
|
|
|
.is_none();
|
2018-03-29 06:33:40 +02:00
|
|
|
assert!(ok)
|
2017-12-21 05:30:54 +01:00
|
|
|
}
|
2017-12-21 02:51:28 +01:00
|
|
|
}
|