1
0
mirror of https://github.com/actix/actix-website synced 2024-12-19 02:13:13 +01:00
actix-website/examples/requests/src/manual.rs

43 lines
1.2 KiB
Rust
Raw Normal View History

2019-06-17 20:34:23 +02:00
// <json-manual>
use actix_web::{error, web, App, Error, HttpResponse};
2019-06-17 20:34:23 +02:00
use bytes::BytesMut;
2019-12-28 18:32:47 +01:00
use futures::StreamExt;
2019-06-17 20:34:23 +02:00
use serde::{Deserialize, Serialize};
use serde_json;
#[derive(Serialize, Deserialize)]
struct MyObj {
name: String,
number: i32,
}
const MAX_SIZE: usize = 262_144; // max payload size is 256k
2019-12-28 18:32:47 +01:00
async fn index_manual(mut payload: web::Payload) -> Result<HttpResponse, Error> {
2019-06-17 20:34:23 +02:00
// payload is a stream of Bytes objects
2019-12-28 18:32:47 +01:00
let mut body = BytesMut::new();
while let Some(chunk) = payload.next().await {
let chunk = chunk?;
// limit max size of in-memory payload
if (body.len() + chunk.len()) > MAX_SIZE {
return Err(error::ErrorBadRequest("overflow"));
}
body.extend_from_slice(&chunk);
}
// body is loaded, now we can deserialize serde-json
let obj = serde_json::from_slice::<MyObj>(&body)?;
Ok(HttpResponse::Ok().json(obj)) // <- send response
2019-06-17 20:34:23 +02:00
}
// </json-manual>
2019-12-28 18:32:47 +01:00
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
2019-06-26 07:27:17 +02:00
use actix_web::HttpServer;
2019-12-28 18:32:47 +01:00
HttpServer::new(|| App::new().route("/", web::post().to(index_manual)))
.bind("127.0.0.1:8088")?
2019-06-26 07:27:17 +02:00
.run()
2019-12-28 18:32:47 +01:00
.await
}