1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-28 17:52:40 +01:00
actix-extras/examples/json/src/main.rs

108 lines
3.8 KiB
Rust
Raw Normal View History

2017-12-21 00:12:43 +01:00
extern crate actix;
extern crate actix_web;
2017-12-25 17:12:13 +01:00
extern crate bytes;
2017-12-21 00:12:43 +01:00
extern crate futures;
extern crate env_logger;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
2017-12-30 15:24:12 +01:00
#[macro_use] extern crate json;
2018-03-31 09:16:55 +02:00
use actix_web::{
middleware, http, error, server,
App, AsyncResponder, HttpRequest, HttpResponse, HttpMessage, Error, Json};
2017-12-25 17:12:13 +01:00
use bytes::BytesMut;
use futures::{Future, Stream};
2017-12-30 15:24:12 +01:00
use json::JsonValue;
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,
}
2017-12-30 15:24:12 +01:00
/// This handler uses `HttpRequest::json()` for loading serde json object.
2018-01-05 23:01:19 +01:00
fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
2017-12-25 17:12:13 +01:00
req.json()
.from_err() // convert all errors into `Error`
2017-12-21 05:30:54 +01:00
.and_then(|val: MyObj| {
println!("model: {:?}", val);
2018-03-31 08:37:15 +02:00
Ok(HttpResponse::Ok().json(val)) // <- send response
2017-12-21 05:30:54 +01:00
})
.responder()
2017-12-21 00:12:43 +01:00
}
2018-03-27 08:10:31 +02:00
/// This handler uses `With` helper for loading serde json object.
2018-03-31 08:37:15 +02:00
fn extract_item(item: Json<MyObj>) -> HttpResponse {
2018-03-27 08:10:31 +02:00
println!("model: {:?}", &item);
2018-03-31 03:54:38 +02:00
HttpResponse::Ok().json(item.0) // <- send response
2018-03-27 08:10:31 +02:00
}
2017-12-25 17:12:13 +01:00
const MAX_SIZE: usize = 262_144; // max payload size is 256k
2017-12-30 15:24:12 +01:00
/// This handler manually load request payload and parse serde json
fn index_manual(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
// HttpRequest is stream of Bytes objects
req
2017-12-25 17:12:13 +01:00
// `Future::from_err` acts like `?` in that it coerces the error type from
// the future into the final error type
.from_err()
// `fold` will asynchronously read each chunk of the request body and
// call supplied closure, then it resolves to result of closure
.fold(BytesMut::new(), move |mut body, chunk| {
// limit max size of in-memory payload
if (body.len() + chunk.len()) > MAX_SIZE {
Err(error::ErrorBadRequest("overflow"))
} else {
body.extend_from_slice(&chunk);
Ok(body)
}
})
// `Future::and_then` can be used to merge an asynchronous workflow with a
// synchronous workflow
.and_then(|body| {
2017-12-30 15:24:12 +01:00
// body is loaded, now we can deserialize serde-json
2017-12-25 17:12:13 +01:00
let obj = serde_json::from_slice::<MyObj>(&body)?;
2018-03-31 08:37:15 +02:00
Ok(HttpResponse::Ok().json(obj)) // <- send response
2017-12-25 17:12:13 +01:00
})
.responder()
}
2017-12-30 15:24:12 +01:00
/// This handler manually load request payload and parse json-rust
fn index_mjsonrust(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
req.concat2()
2017-12-30 15:24:12 +01:00
.from_err()
.and_then(|body| {
// body is loaded, now we can deserialize json-rust
let result = json::parse(std::str::from_utf8(&body).unwrap()); // return Result
let injson: JsonValue = match result { Ok(v) => v, Err(e) => object!{"err" => e.to_string() } };
2018-03-31 03:54:38 +02:00
Ok(HttpResponse::Ok()
2017-12-30 15:24:12 +01:00
.content_type("application/json")
2018-03-31 08:37:15 +02:00
.body(injson.dump()))
2017-12-30 15:24:12 +01:00
})
.responder()
}
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");
2018-03-31 03:54:38 +02:00
let _ = server::new(|| {
2018-03-31 09:16:55 +02:00
App::new()
2017-12-21 00:12:43 +01:00
// enable logger
2017-12-27 04:59:41 +01:00
.middleware(middleware::Logger::default())
2018-03-27 08:10:31 +02:00
.resource("/extractor/{name}/{number}/",
2018-03-31 03:54:38 +02:00
|r| r.method(http::Method::GET).with(extract_item))
.resource("/manual", |r| r.method(http::Method::POST).f(index_manual))
.resource("/mjsonrust", |r| r.method(http::Method::POST).f(index_mjsonrust))
.resource("/", |r| r.method(http::Method::POST).f(index))})
2017-12-21 00:12:43 +01:00
.bind("127.0.0.1:8080").unwrap()
2017-12-30 15:24:12 +01:00
.shutdown_timeout(1)
2017-12-21 00:12:43 +01:00
.start();
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
}