mirror of
https://github.com/actix/examples
synced 2024-11-27 16:02:57 +01:00
re-add request body in middleware example
This commit is contained in:
parent
c1345414e2
commit
4272586f0c
1
Cargo.lock
generated
1
Cargo.lock
generated
@ -4103,6 +4103,7 @@ dependencies = [
|
||||
name = "middleware-example"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"actix-http",
|
||||
"actix-web",
|
||||
"env_logger",
|
||||
"futures-util",
|
||||
|
@ -5,6 +5,8 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "4"
|
||||
actix-http = "3"
|
||||
|
||||
env_logger = "0.10"
|
||||
futures-util = { version = "0.3.17", default-features = false, features = ["std"] }
|
||||
log = "0.4"
|
||||
|
@ -26,7 +26,8 @@ async fn main() -> std::io::Result<()> {
|
||||
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."
|
||||
}))
|
||||
.service(
|
||||
@ -36,6 +37,7 @@ async fn main() -> std::io::Result<()> {
|
||||
)
|
||||
})
|
||||
.bind(("127.0.0.1", 8080))?
|
||||
.workers(1)
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
|
@ -3,12 +3,12 @@ use std::{
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
use actix_http::h1;
|
||||
use actix_web::{
|
||||
dev::{self, Service, ServiceRequest, ServiceResponse, Transform},
|
||||
web::BytesMut,
|
||||
Error, HttpMessage,
|
||||
web, Error,
|
||||
};
|
||||
use futures_util::{future::LocalBoxFuture, stream::StreamExt};
|
||||
use futures_util::future::LocalBoxFuture;
|
||||
|
||||
pub struct Logging;
|
||||
|
||||
@ -52,13 +52,13 @@ where
|
||||
let svc = self.service.clone();
|
||||
|
||||
Box::pin(async move {
|
||||
let mut body = BytesMut::new();
|
||||
let mut stream = req.take_payload();
|
||||
while let Some(chunk) = stream.next().await {
|
||||
body.extend_from_slice(&chunk?);
|
||||
}
|
||||
// extract bytes from request body
|
||||
let body = req.extract::<web::Bytes>().await.unwrap();
|
||||
println!("request body (middleware): {body:?}");
|
||||
|
||||
// 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?;
|
||||
|
||||
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)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user