mirror of
https://github.com/actix/examples
synced 2024-12-04 02:32:12 +01:00
75 lines
2.0 KiB
Rust
75 lines
2.0 KiB
Rust
use std::{
|
|
future::{ready, Ready},
|
|
rc::Rc,
|
|
};
|
|
|
|
use actix_http::h1;
|
|
use actix_web::{
|
|
dev::{self, Service, ServiceRequest, ServiceResponse, Transform},
|
|
web, Error,
|
|
};
|
|
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>;
|
|
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();
|
|
|
|
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));
|
|
|
|
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)
|
|
}
|