2017-12-21 00:12:43 +01:00
|
|
|
extern crate actix;
|
|
|
|
extern crate actix_web;
|
|
|
|
extern crate futures;
|
|
|
|
extern crate env_logger;
|
|
|
|
extern crate serde_json;
|
|
|
|
#[macro_use] extern crate serde_derive;
|
|
|
|
|
|
|
|
use actix_web::*;
|
|
|
|
use futures::Stream;
|
2017-12-21 00:45:26 +01:00
|
|
|
use futures::future::{Future, ok, err};
|
2017-12-21 00:12:43 +01:00
|
|
|
|
2017-12-21 01:05:07 +01:00
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
2017-12-21 00:12:43 +01:00
|
|
|
struct MyObj {
|
|
|
|
name: String,
|
|
|
|
number: i32,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn index(mut req: HttpRequest) -> Result<Box<Future<Item=HttpResponse, Error=Error>>> {
|
2017-12-21 00:45:26 +01:00
|
|
|
// check content-type
|
2017-12-21 00:12:43 +01:00
|
|
|
if req.content_type() != "application/json" {
|
|
|
|
return Err(error::ErrorBadRequest("wrong content-type").into())
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(Box::new(
|
2017-12-21 01:05:07 +01:00
|
|
|
// `concat2` will asynchronously read each chunk of the request body and
|
|
|
|
// return a single, concatenated, chunk
|
|
|
|
req.payload_mut().readany().concat2()
|
|
|
|
// `Future::from_err` acts like `?` in that it coerces the error type from
|
|
|
|
// the future into the final error type
|
|
|
|
.from_err()
|
|
|
|
// `Future::and_then` can be used to merge an asynchronous workflow with a
|
|
|
|
// synchronous workflow
|
2017-12-21 00:45:26 +01:00
|
|
|
.and_then(|body| { // <- body is loaded, now we can deserialize json
|
2017-12-21 00:12:43 +01:00
|
|
|
match serde_json::from_slice::<MyObj>(&body) {
|
|
|
|
Ok(obj) => {
|
2017-12-21 00:45:26 +01:00
|
|
|
println!("model: {:?}", obj); // <- do something with payload
|
2017-12-21 01:05:07 +01:00
|
|
|
ok(httpcodes::HTTPOk.build() // <- send response
|
|
|
|
.content_type("application/json")
|
|
|
|
.json(obj).unwrap())
|
2017-12-21 00:12:43 +01:00
|
|
|
},
|
2017-12-21 01:05:07 +01:00
|
|
|
Err(e) => err(error::ErrorBadRequest(e).into())
|
2017-12-21 00:12:43 +01:00
|
|
|
}
|
|
|
|
})))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
::std::env::set_var("RUST_LOG", "actix_web=info");
|
|
|
|
let _ = env_logger::init();
|
|
|
|
let sys = actix::System::new("json-example");
|
|
|
|
|
|
|
|
HttpServer::new(|| {
|
|
|
|
Application::new()
|
|
|
|
// enable logger
|
|
|
|
.middleware(middlewares::Logger::default())
|
|
|
|
.resource("/", |r| r.method(Method::POST).f(index))})
|
|
|
|
.bind("127.0.0.1:8080").unwrap()
|
|
|
|
.start();
|
|
|
|
|
|
|
|
println!("Started http server: 127.0.0.1:8080");
|
|
|
|
let _ = sys.run();
|
|
|
|
}
|