1
0
mirror of https://github.com/actix/examples synced 2024-12-04 18:51:55 +01:00
examples/middleware/various/src/read_request_body.rs

75 lines
2.0 KiB
Rust
Raw Normal View History

use std::{
future::{ready, Ready},
rc::Rc,
};
2019-12-07 18:59:24 +01:00
use actix_http::h1;
2022-02-22 13:12:17 +01:00
use actix_web::{
dev::{self, Service, ServiceRequest, ServiceResponse, Transform},
web, Error,
2022-02-22 13:12:17 +01:00
};
use futures_util::future::LocalBoxFuture;
pub struct Logging;
impl<S: 'static, B> Transform<S, ServiceRequest> for Logging
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type InitError = ();
type Transform = LoggingMiddleware<S>;
2019-12-07 18:59:24 +01:00
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(LoggingMiddleware {
service: Rc::new(service),
}))
}
}
pub struct LoggingMiddleware<S> {
// This is special: We need this to avoid lifetime issues.
service: Rc<S>,
}
impl<S, B> Service<ServiceRequest> for LoggingMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
dev::forward_ready!(service);
fn call(&self, mut req: ServiceRequest) -> Self::Future {
let svc = self.service.clone();
2019-12-07 18:59:24 +01:00
Box::pin(async move {
// 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));
2019-12-07 18:59:24 +01:00
let res = svc.call(req).await?;
println!("response: {:?}", res.headers());
Ok(res)
})
}
}
fn bytes_to_payload(buf: web::Bytes) -> dev::Payload {
let (_, mut pl) = h1::Payload::create(true);
pl.unread_data(buf);
dev::Payload::from(pl)
}