mirror of
https://github.com/actix/actix-website
synced 2024-12-18 18:03:12 +01:00
42 lines
1.1 KiB
Rust
42 lines
1.1 KiB
Rust
// <json-manual>
|
|
use actix_web::{error, post, web, App, Error, HttpResponse};
|
|
use futures::StreamExt;
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
struct MyObj {
|
|
name: String,
|
|
number: i32,
|
|
}
|
|
|
|
const MAX_SIZE: usize = 262_144; // max payload size is 256k
|
|
|
|
#[post("/")]
|
|
async fn index_manual(mut payload: web::Payload) -> Result<HttpResponse, Error> {
|
|
// payload is a stream of Bytes objects
|
|
let mut body = web::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
|
|
}
|
|
// </json-manual>
|
|
|
|
#[actix_web::main]
|
|
async fn main() -> std::io::Result<()> {
|
|
use actix_web::HttpServer;
|
|
|
|
HttpServer::new(|| App::new().service(index_manual))
|
|
.bind(("127.0.0.1", 8080))?
|
|
.run()
|
|
.await
|
|
}
|