use std::future::{ready, Ready}; use actix_web::{ dev::{self, Service, ServiceRequest, ServiceResponse, Transform}, Error, }; use futures_util::future::LocalBoxFuture; // There are two steps in middleware processing. // 1. Middleware initialization, middleware factory gets called with // next service in chain as parameter. // 2. Middleware's call method gets 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 Response = ServiceResponse; type Error = Error; type InitError = (); type Transform = SayHiMiddleware; type Future = Ready>; fn new_transform(&self, service: S) -> Self::Future { ready(Ok(SayHiMiddleware { service })) } } pub struct SayHiMiddleware { service: S, } impl Service for SayHiMiddleware where S: Service, Error = Error>, S::Future: 'static, B: 'static, { type Response = ServiceResponse; type Error = Error; type Future = LocalBoxFuture<'static, Result>; dev::forward_ready!(service); fn call(&self, req: ServiceRequest) -> Self::Future { println!("Hi from start. You requested: {}", req.path()); let fut = self.service.call(req); Box::pin(async move { let res = fut.await?; println!("Hi from response"); Ok(res) }) } }