1
0
mirror of https://github.com/actix/examples synced 2024-11-23 22:41:07 +01:00

re-add request body in middleware example

This commit is contained in:
Rob Ede 2022-12-17 22:04:59 +00:00
parent c1345414e2
commit 4272586f0c
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
4 changed files with 21 additions and 10 deletions

1
Cargo.lock generated
View File

@ -4103,6 +4103,7 @@ dependencies = [
name = "middleware-example" name = "middleware-example"
version = "1.0.0" version = "1.0.0"
dependencies = [ dependencies = [
"actix-http",
"actix-web", "actix-web",
"env_logger", "env_logger",
"futures-util", "futures-util",

View File

@ -5,6 +5,8 @@ edition = "2021"
[dependencies] [dependencies]
actix-web = "4" actix-web = "4"
actix-http = "3"
env_logger = "0.10" env_logger = "0.10"
futures-util = { version = "0.3.17", default-features = false, features = ["std"] } futures-util = { version = "0.3.17", default-features = false, features = ["std"] }
log = "0.4" log = "0.4"

View File

@ -26,7 +26,8 @@ async fn main() -> std::io::Result<()> {
res res
}) })
}) })
.service(web::resource("/login").to(|| async { .service(web::resource("/login").to(|body: String| async move {
println!("request body (handler): {body}");
"You are on /login. Go to src/redirect.rs to change this behavior." "You are on /login. Go to src/redirect.rs to change this behavior."
})) }))
.service( .service(
@ -36,6 +37,7 @@ async fn main() -> std::io::Result<()> {
) )
}) })
.bind(("127.0.0.1", 8080))? .bind(("127.0.0.1", 8080))?
.workers(1)
.run() .run()
.await .await
} }

View File

@ -3,12 +3,12 @@ use std::{
rc::Rc, rc::Rc,
}; };
use actix_http::h1;
use actix_web::{ use actix_web::{
dev::{self, Service, ServiceRequest, ServiceResponse, Transform}, dev::{self, Service, ServiceRequest, ServiceResponse, Transform},
web::BytesMut, web, Error,
Error, HttpMessage,
}; };
use futures_util::{future::LocalBoxFuture, stream::StreamExt}; use futures_util::future::LocalBoxFuture;
pub struct Logging; pub struct Logging;
@ -52,13 +52,13 @@ where
let svc = self.service.clone(); let svc = self.service.clone();
Box::pin(async move { Box::pin(async move {
let mut body = BytesMut::new(); // extract bytes from request body
let mut stream = req.take_payload(); let body = req.extract::<web::Bytes>().await.unwrap();
while let Some(chunk) = stream.next().await { println!("request body (middleware): {body:?}");
body.extend_from_slice(&chunk?);
} // re-insert body back into request to be used by handlers
req.set_payload(bytes_to_payload(body));
println!("request body: {body:?}");
let res = svc.call(req).await?; let res = svc.call(req).await?;
println!("response: {:?}", res.headers()); println!("response: {:?}", res.headers());
@ -66,3 +66,9 @@ where
}) })
} }
} }
fn bytes_to_payload(buf: web::Bytes) -> dev::Payload {
let (_, mut pl) = h1::Payload::create(true);
pl.unread_data(buf);
dev::Payload::from(pl)
}