2019-09-11 15:12:08 +02:00
|
|
|
use actix_service::{Service, Transform};
|
2019-09-18 04:37:35 +02:00
|
|
|
use actix_web::body::{Body, MessageBody, ResponseBody};
|
2019-09-11 15:12:08 +02:00
|
|
|
use actix_web::error::PayloadError;
|
2019-09-18 04:37:35 +02:00
|
|
|
use actix_web::{dev::ServiceRequest, dev::ServiceResponse, Error};
|
2019-09-11 15:12:08 +02:00
|
|
|
use bytes::BytesMut;
|
|
|
|
use futures::future::{ok, FutureResult};
|
|
|
|
use futures::stream::Stream;
|
|
|
|
use futures::{Future, Poll};
|
|
|
|
|
|
|
|
pub struct Logging;
|
|
|
|
|
|
|
|
impl<S: 'static, B> Transform<S> for Logging
|
|
|
|
where
|
|
|
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
|
|
|
S::Future: 'static,
|
2019-09-18 04:37:35 +02:00
|
|
|
B: MessageBody + 'static,
|
2019-09-11 15:12:08 +02:00
|
|
|
{
|
|
|
|
type Request = ServiceRequest;
|
|
|
|
type Response = ServiceResponse<B>;
|
|
|
|
type Error = Error;
|
|
|
|
type InitError = ();
|
|
|
|
type Transform = LoggingMiddleware<S>;
|
|
|
|
type Future = FutureResult<Self::Transform, Self::InitError>;
|
|
|
|
|
|
|
|
fn new_transform(&self, service: S) -> Self::Future {
|
|
|
|
ok(LoggingMiddleware {
|
2019-09-18 04:37:35 +02:00
|
|
|
service,
|
2019-09-11 15:12:08 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct LoggingMiddleware<S> {
|
2019-09-18 04:37:35 +02:00
|
|
|
service: S,
|
2019-09-11 15:12:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<S, B> Service for LoggingMiddleware<S>
|
|
|
|
where
|
|
|
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>
|
|
|
|
+ 'static,
|
|
|
|
S::Future: 'static,
|
2019-09-18 04:37:35 +02:00
|
|
|
B: MessageBody + 'static,
|
2019-09-11 15:12:08 +02:00
|
|
|
{
|
|
|
|
type Request = ServiceRequest;
|
|
|
|
type Response = ServiceResponse<B>;
|
|
|
|
type Error = Error;
|
|
|
|
type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
|
|
|
|
|
|
|
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
|
|
|
self.service.poll_ready()
|
|
|
|
}
|
|
|
|
|
2019-09-18 04:37:35 +02:00
|
|
|
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
|
|
|
Box::new(self.service.call(req).and_then(|res| {
|
|
|
|
Ok(res.map_body(|_, body| {
|
|
|
|
ResponseBody::Other(Body::Bytes(
|
|
|
|
body.fold(BytesMut::new(), move |mut body, chunk| {
|
|
|
|
body.extend_from_slice(&chunk);
|
|
|
|
Ok::<_, PayloadError>(body)
|
|
|
|
})
|
|
|
|
.and_then(move |bytes| {
|
|
|
|
println!("response body: {:?}", &bytes);
|
|
|
|
ok(bytes.freeze())
|
|
|
|
})
|
|
|
|
.wait()
|
|
|
|
.unwrap(),
|
|
|
|
))
|
|
|
|
}))
|
|
|
|
}))
|
2019-09-11 15:12:08 +02:00
|
|
|
}
|
|
|
|
}
|