diff --git a/examples/json/src/main.rs b/examples/json/src/main.rs index c271c12b0..239874525 100644 --- a/examples/json/src/main.rs +++ b/examples/json/src/main.rs @@ -9,7 +9,7 @@ extern crate serde_json; use actix_web::*; use bytes::BytesMut; use futures::Stream; -use futures::future::{Future, ok, err, result}; +use futures::future::{Future, ok, err}; #[derive(Debug, Deserialize)] struct MyObj { @@ -18,25 +18,23 @@ struct MyObj { } fn index(mut req: HttpRequest) -> Result>> { - // check content-type, early error exit + // check content-type if req.content_type() != "application/json" { return Err(error::ErrorBadRequest("wrong content-type").into()) } Ok(Box::new( - // load request body - req.payload_mut() + req.payload_mut() // <- load request body .readany() .fold(BytesMut::new(), |mut body, chunk| { body.extend(chunk); - result::<_, error::PayloadError>(Ok(body)) + ok::<_, error::PayloadError>(body) }) .map_err(|e| Error::from(e)) - .and_then(|body| { - // body is loaded, now we can deserialize json + .and_then(|body| { // <- body is loaded, now we can deserialize json match serde_json::from_slice::(&body) { Ok(obj) => { - println!("MODEL: {:?}", obj); // <- do something with payload + println!("model: {:?}", obj); // <- do something with payload ok(httpcodes::HTTPOk.response()) // <- send response }, Err(e) => { diff --git a/guide/src/qs_7.md b/guide/src/qs_7.md index bb1a14367..2cbc527b6 100644 --- a/guide/src/qs_7.md +++ b/guide/src/qs_7.md @@ -59,8 +59,8 @@ fn index(req: HttpRequest) -> HttpResponse { ## JSON Request -Unfortunately, because of async nature of actix web framework, deserializing json -requests is not very ergonomic process. First you need to load whole body into +Unfortunately, because of async nature of actix web framework, json requests deserialization +is not very ergonomic process. First you need to load whole body into a temporal storage and only then you can deserialize it. Here is simple example. We will deserialize *MyObj* struct. @@ -73,17 +73,16 @@ struct MyObj { } ``` -We need to load request body first. +We need to load request body first and then deserialize json into object. ```rust,ignore fn index(mut req: HttpRequest) -> Future { - req.payload_mut().readany() .fold(BytesMut::new(), |mut body, chunk| { // <- load request body body.extend(chunk); - result::<_, error::PayloadError>(Ok(body)) + ok(body) }) - .and_then(|body| { // <- body is loaded, now we can deserialize json + .and_then(|body| { // <- body is loaded, now we can deserialize json let obj = serde_json::from_slice::(&body).unwrap(); println!("MODEL: {:?}", obj); // <- do something with payload ok(httpcodes::HTTPOk.response()) // <- send response