use actix_service::{Service, Transform}; use actix_web::{dev::ServiceRequest, dev::ServiceResponse, Error}; use futures::future::{ok, FutureResult}; use futures::{Future, Poll}; // There are two step in middleware processing. // 1. Middleware initialization, middleware factory get called with // next service in chain as parameter. // 2. Middleware's call method get called with normal request. pub struct SayHi; // Middleware factory is `Transform` trait from actix-service crate // `S` - type of the next service // `B` - type of response's body impl Transform for SayHi where S: Service, Error = Error>, S::Future: 'static, B: 'static, { type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type InitError = (); type Transform = SayHiMiddleware; type Future = FutureResult; fn new_transform(&self, service: S) -> Self::Future { ok(SayHiMiddleware { service }) } } pub struct SayHiMiddleware { service: S, } impl Service for SayHiMiddleware where S: Service, Error = Error>, S::Future: 'static, B: 'static, { type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type Future = Box>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.poll_ready() } fn call(&mut self, req: ServiceRequest) -> Self::Future { println!("Hi from start. You requested: {}", req.path()); Box::new(self.service.call(req).and_then(|res| { println!("Hi from response"); Ok(res) })) } }