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

update example

This commit is contained in:
Nikolay Kim 2017-12-20 16:13:21 -08:00
parent 50891986bc
commit 4dd3382ac7
2 changed files with 10 additions and 17 deletions

View File

@ -6,8 +6,7 @@ extern crate serde_json;
#[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_derive;
use actix_web::*; use actix_web::*;
use futures::Stream; use futures::{Future, Stream};
use futures::future::{Future, ok, err};
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
struct MyObj { struct MyObj {
@ -31,16 +30,12 @@ fn index(mut req: HttpRequest) -> Result<Box<Future<Item=HttpResponse, Error=Err
// `Future::and_then` can be used to merge an asynchronous workflow with a // `Future::and_then` can be used to merge an asynchronous workflow with a
// synchronous workflow // 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) { let obj = serde_json::from_slice::<MyObj>(&body).map_err(error::ErrorBadRequest)?;
Ok(obj) => {
println!("model: {:?}", obj); // <- do something with payload println!("model: {:?}", obj);
ok(httpcodes::HTTPOk.build() // <- send response Ok(httpcodes::HTTPOk.build().json(obj)?) // <- send response
.content_type("application/json") })
.json(obj).unwrap()) ))
},
Err(e) => err(error::ErrorBadRequest(e).into())
}
})))
} }
fn main() { fn main() {

View File

@ -85,11 +85,9 @@ fn index(mut req: HttpRequest) -> Future<Item=HttpResponse, Error=Error> {
.from_err() .from_err()
// `Future::and_then` can be used to merge an asynchronous workflow with a // `Future::and_then` can be used to merge an asynchronous workflow with a
// synchronous workflow // synchronous workflow
.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::<MyObj>(&body).unwrap(); let obj = serde_json::from_slice::<MyObj>(&body)?;
ok(httpcodes::HTTPOk.build() // <- send response Ok(httpcodes::HTTPOk.build().json(obj)?) // <- send response
.content_type("application/json")
.json(obj).unwrap())
}) })
} }
``` ```