1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-01-18 05:41:50 +01:00

simplify json example

This commit is contained in:
Nikolay Kim 2017-12-20 16:05:07 -08:00
parent df2aa42dad
commit 50891986bc
2 changed files with 27 additions and 24 deletions

View File

@ -1,17 +1,15 @@
extern crate actix; extern crate actix;
extern crate actix_web; extern crate actix_web;
extern crate bytes;
extern crate futures; extern crate futures;
extern crate env_logger; extern crate env_logger;
extern crate serde_json; extern crate serde_json;
#[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_derive;
use actix_web::*; use actix_web::*;
use bytes::BytesMut;
use futures::Stream; use futures::Stream;
use futures::future::{Future, ok, err}; use futures::future::{Future, ok, err};
#[derive(Debug, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
struct MyObj { struct MyObj {
name: String, name: String,
number: i32, number: i32,
@ -24,22 +22,23 @@ fn index(mut req: HttpRequest) -> Result<Box<Future<Item=HttpResponse, Error=Err
} }
Ok(Box::new( Ok(Box::new(
req.payload_mut() // <- load request body // `concat2` will asynchronously read each chunk of the request body and
.readany() // return a single, concatenated, chunk
.fold(BytesMut::new(), |mut body, chunk| { req.payload_mut().readany().concat2()
body.extend(chunk); // `Future::from_err` acts like `?` in that it coerces the error type from
ok::<_, error::PayloadError>(body) // the future into the final error type
}) .from_err()
.map_err(|e| Error::from(e)) // `Future::and_then` can be used to merge an asynchronous workflow with a
// synchronous workflow
.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::<MyObj>(&body) { match serde_json::from_slice::<MyObj>(&body) {
Ok(obj) => { Ok(obj) => {
println!("model: {:?}", obj); // <- do something with payload println!("model: {:?}", obj); // <- do something with payload
ok(httpcodes::HTTPOk.response()) // <- send response ok(httpcodes::HTTPOk.build() // <- send response
.content_type("application/json")
.json(obj).unwrap())
}, },
Err(e) => { Err(e) => err(error::ErrorBadRequest(e).into())
err(error::ErrorBadRequest(e).into())
}
} }
}))) })))
} }

View File

@ -77,16 +77,20 @@ We need to load request body first and then deserialize json into object.
```rust,ignore ```rust,ignore
fn index(mut req: HttpRequest) -> Future<Item=HttpResponse, Error=Error> { fn index(mut req: HttpRequest) -> Future<Item=HttpResponse, Error=Error> {
req.payload_mut().readany() // `concat2` will asynchronously read each chunk of the request body and
.fold(BytesMut::new(), |mut body, chunk| { // <- load request body // return a single, concatenated, chunk
body.extend(chunk); req.payload_mut().readany().concat2()
ok(body) // `Future::from_err` acts like `?` in that it coerces the error type from
}) // the future into the final error type
.and_then(|body| { // <- body is loaded, now we can deserialize json .from_err()
let obj = serde_json::from_slice::<MyObj>(&body).unwrap(); // `Future::and_then` can be used to merge an asynchronous workflow with a
println!("MODEL: {:?}", obj); // <- do something with payload // synchronous workflow
ok(httpcodes::HTTPOk.response()) // <- send response .and_then(|body| { // <- body is loaded, now we can deserialize json
}) let obj = serde_json::from_slice::<MyObj>(&body).unwrap();
ok(httpcodes::HTTPOk.build() // <- send response
.content_type("application/json")
.json(obj).unwrap())
})
} }
``` ```