|
| 1 | +use actix_web::{error, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer}; |
| 2 | +use futures::StreamExt; |
| 3 | +use json::JsonValue; |
| 4 | +use serde::{Deserialize, Serialize}; |
| 5 | + |
| 6 | +#[derive(Debug, Serialize, Deserialize)] |
| 7 | +struct MyObj { |
| 8 | + name: String, |
| 9 | + number: i32, |
| 10 | +} |
| 11 | + |
| 12 | +/// This handler uses json extractor |
| 13 | +async fn index(item: web::Json<MyObj>) -> HttpResponse { |
| 14 | + println!("model: {:?}", &item); |
| 15 | + HttpResponse::Ok().json(item.0) // <- send response |
| 16 | +} |
| 17 | + |
| 18 | +/// This handler uses json extractor with limit |
| 19 | +async fn extract_item(item: web::Json<MyObj>, req: HttpRequest) -> HttpResponse { |
| 20 | + println!("request: {:?}", req); |
| 21 | + println!("model: {:?}", item); |
| 22 | + |
| 23 | + HttpResponse::Ok().json(item.0) // <- send json response |
| 24 | +} |
| 25 | + |
| 26 | +const MAX_SIZE: usize = 262_144; // max payload size is 256k |
| 27 | + |
| 28 | +/// This handler manually load request payload and parse json object |
| 29 | +async fn index_manual(mut payload: web::Payload) -> Result<HttpResponse, Error> { |
| 30 | + // payload is a stream of Bytes objects |
| 31 | + let mut body = web::BytesMut::new(); |
| 32 | + while let Some(chunk) = payload.next().await { |
| 33 | + let chunk = chunk?; |
| 34 | + // limit max size of in-memory payload |
| 35 | + if (body.len() + chunk.len()) > MAX_SIZE { |
| 36 | + return Err(error::ErrorBadRequest("overflow")); |
| 37 | + } |
| 38 | + body.extend_from_slice(&chunk); |
| 39 | + } |
| 40 | + |
| 41 | + // body is loaded, now we can deserialize serde-json |
| 42 | + let obj = serde_json::from_slice::<MyObj>(&body)?; |
| 43 | + Ok(HttpResponse::Ok().json(obj)) // <- send response |
| 44 | +} |
| 45 | + |
| 46 | +/// This handler manually load request payload and parse json-rust |
| 47 | +async fn index_mjsonrust(body: web::Bytes) -> Result<HttpResponse, Error> { |
| 48 | + // body is loaded, now we can deserialize json-rust |
| 49 | + let result = json::parse(std::str::from_utf8(&body).unwrap()); // return Result |
| 50 | + let injson: JsonValue = match result { |
| 51 | + Ok(v) => v, |
| 52 | + Err(e) => json::object! {"err" => e.to_string() }, |
| 53 | + }; |
| 54 | + Ok(HttpResponse::Ok() |
| 55 | + .content_type("application/json") |
| 56 | + .body(injson.dump())) |
| 57 | +} |
| 58 | + |
| 59 | +#[actix_web::main] |
| 60 | +async fn main() -> std::io::Result<()> { |
| 61 | + std::env::set_var("RUST_LOG", "actix_web=info"); |
| 62 | + env_logger::init(); |
| 63 | + |
| 64 | + HttpServer::new(|| { |
| 65 | + App::new() |
| 66 | + // enable logger |
| 67 | + .wrap(middleware::Logger::default()) |
| 68 | + .app_data(web::JsonConfig::default().limit(4096)) // <- limit size of the payload (global configuration) |
| 69 | + .service(web::resource("/extractor").route(web::post().to(index))) |
| 70 | + .service( |
| 71 | + web::resource("/extractor2") |
| 72 | + .app_data(web::JsonConfig::default().limit(1024)) // <- limit size of the payload (resource level) |
| 73 | + .route(web::post().to(extract_item)), |
| 74 | + ) |
| 75 | + .service(web::resource("/manual").route(web::post().to(index_manual))) |
| 76 | + .service(web::resource("/mjsonrust").route(web::post().to(index_mjsonrust))) |
| 77 | + .service(web::resource("/").route(web::post().to(index))) |
| 78 | + }) |
| 79 | + .bind(("127.0.0.1", 8080))? |
| 80 | + .run() |
| 81 | + .await |
| 82 | +} |
| 83 | + |
| 84 | +#[cfg(test)] |
| 85 | +mod tests { |
| 86 | + use super::*; |
| 87 | + use actix_web::body::to_bytes; |
| 88 | + use actix_web::dev::Service; |
| 89 | + use actix_web::{http, test, web, App}; |
| 90 | + |
| 91 | + #[actix_web::test] |
| 92 | + async fn test_index() { |
| 93 | + let app = |
| 94 | + test::init_service(App::new().service(web::resource("/").route(web::post().to(index)))) |
| 95 | + .await; |
| 96 | + |
| 97 | + let req = test::TestRequest::post() |
| 98 | + .uri("/") |
| 99 | + .set_json(&MyObj { |
| 100 | + name: "my-name".to_owned(), |
| 101 | + number: 43, |
| 102 | + }) |
| 103 | + .to_request(); |
| 104 | + let resp = app.call(req).await.unwrap(); |
| 105 | + |
| 106 | + assert_eq!(resp.status(), http::StatusCode::OK); |
| 107 | + |
| 108 | + let body_bytes = to_bytes(resp.into_body()).await.unwrap(); |
| 109 | + assert_eq!(body_bytes, r##"{"name":"my-name","number":43}"##); |
| 110 | + } |
| 111 | +} |
0 commit comments