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

42 lines
1.1 KiB
Rust
Raw Normal View History

2019-06-17 20:34:23 +02:00
// <json-manual>
2020-09-12 17:21:54 +02:00
use actix_web::{error, post, web, App, Error, HttpResponse};
2019-12-28 18:32:47 +01:00
use futures::StreamExt;
2019-06-17 20:34:23 +02:00
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct MyObj {
name: String,
number: i32,
}
const MAX_SIZE: usize = 262_144; // max payload size is 256k
2020-09-12 17:21:54 +02:00
#[post("/")]
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
2020-09-12 17:21:54 +02:00
let mut body = web::BytesMut::new();
2019-12-28 18:32:47 +01:00
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>
2020-09-12 17:21:54 +02:00
#[actix_web::main]
2019-12-28 18:32:47 +01:00
async fn main() -> std::io::Result<()> {
2019-06-26 07:27:17 +02:00
use actix_web::HttpServer;
2020-09-12 17:21:54 +02:00
HttpServer::new(|| App::new().service(index_manual))
2022-02-26 04:56:24 +01:00
.bind(("127.0.0.1", 8080))?
2019-06-26 07:27:17 +02:00
.run()
2019-12-28 18:32:47 +01:00
.await
}