1
0
mirror of https://github.com/actix/examples synced 2025-02-03 01:49:05 +01:00
examples/json/src/main.rs

109 lines
3.7 KiB
Rust
Raw Normal View History

2018-05-08 11:08:43 -07:00
#[macro_use]
extern crate json;
2018-05-20 21:03:29 -07:00
use actix_web::{
2019-03-07 14:50:29 -08:00
error, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer,
2018-05-20 21:03:29 -07:00
};
2019-03-26 04:29:00 +01:00
use bytes::BytesMut;
use futures::{Future, Stream};
use json::JsonValue;
2019-03-07 14:50:29 -08:00
use serde_derive::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct MyObj {
name: String,
number: i32,
}
/// This handler uses json extractor
2019-03-07 14:50:29 -08:00
fn index(item: web::Json<MyObj>) -> HttpResponse {
println!("model: {:?}", &item);
2018-05-08 11:08:43 -07:00
HttpResponse::Ok().json(item.0) // <- send response
}
2018-06-02 08:28:33 -07:00
/// This handler uses json extractor with limit
2019-03-07 14:50:29 -08:00
fn extract_item(item: web::Json<MyObj>, req: HttpRequest) -> HttpResponse {
println!("request: {:?}", req);
println!("model: {:?}", item);
HttpResponse::Ok().json(item.0) // <- send json response
2018-06-02 08:28:33 -07:00
}
2018-05-08 11:08:43 -07:00
const MAX_SIZE: usize = 262_144; // max payload size is 256k
/// This handler manually load request payload and parse json object
2019-03-26 04:29:00 +01:00
fn index_manual(
payload: web::Payload,
) -> impl Future<Item = HttpResponse, Error = Error> {
2019-03-07 14:50:29 -08:00
// payload is a stream of Bytes objects
payload
// `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| {
// body is loaded, now we can deserialize serde-json
let obj = serde_json::from_slice::<MyObj>(&body)?;
Ok(HttpResponse::Ok().json(obj)) // <- send response
})
}
/// This handler manually load request payload and parse json-rust
2019-03-26 04:29:00 +01:00
fn index_mjsonrust(pl: web::Payload) -> impl Future<Item = HttpResponse, Error = Error> {
2019-03-07 14:50:29 -08:00
pl.concat2().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) => json::object! {"err" => e.to_string() },
};
Ok(HttpResponse::Ok()
.content_type("application/json")
.body(injson.dump()))
})
}
2019-03-07 14:50:29 -08:00
fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
2019-03-07 14:50:29 -08:00
HttpServer::new(|| {
App::new()
// enable logger
2019-03-26 04:29:00 +01:00
.wrap(middleware::Logger::default())
2019-03-07 14:50:29 -08:00
.service(
web::resource("/extractor").route(
web::post()
2019-03-26 04:29:00 +01:00
.data(web::JsonConfig::default().limit(4096)) // <- limit size of the payload
2019-03-07 14:50:29 -08:00
.to(index),
),
)
.service(
web::resource("/extractor2").route(
web::post()
2019-03-26 04:29:00 +01:00
.data(web::JsonConfig::default().limit(4096)) // <- limit size of the payload
2019-03-07 14:50:29 -08:00
.to_async(extract_item),
),
)
.service(web::resource("/manual").route(web::post().to_async(index_manual)))
.service(
web::resource("/mjsonrust").route(web::post().to_async(index_mjsonrust)),
)
.service(web::resource("/").route(web::post().to(index)))
})
.bind("127.0.0.1:8080")?
.run()
}