1
0
mirror of https://github.com/actix/examples synced 2025-02-09 04:15:37 +01:00

64 lines
1.7 KiB
Rust
Raw Normal View History

use std::future::{ready, Ready};
2019-12-07 23:59:24 +06:00
use actix_web::{
dev::{self, Service, ServiceRequest, ServiceResponse, Transform},
Error,
};
2022-02-22 12:12:17 +00:00
use futures_util::future::LocalBoxFuture;
2018-07-09 20:18:31 +02:00
2019-06-06 15:20:25 -06:00
// There are two steps in middleware processing.
// 1. Middleware initialization, middleware factory gets called with
2019-03-10 19:19:50 -07:00
// next service in chain as parameter.
2019-06-06 15:20:25 -06:00
// 2. Middleware's call method gets called with normal request.
2018-07-09 20:18:31 +02:00
pub struct SayHi;
2019-03-10 19:19:50 -07:00
// Middleware factory is `Transform` trait from actix-service crate
// `S` - type of the next service
// `B` - type of response's body
impl<S, B> Transform<S, ServiceRequest> for SayHi
2019-03-10 19:19:50 -07:00
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
2019-03-10 19:19:50 -07:00
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
2019-04-25 11:19:21 -07:00
type Error = Error;
2019-03-10 19:19:50 -07:00
type InitError = ();
type Transform = SayHiMiddleware<S>;
2019-12-07 23:59:24 +06:00
type Future = Ready<Result<Self::Transform, Self::InitError>>;
2019-03-10 19:19:50 -07:00
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(SayHiMiddleware { service }))
2018-07-09 20:18:31 +02:00
}
2019-03-10 19:19:50 -07:00
}
2018-07-09 21:36:03 +02:00
2019-03-10 19:19:50 -07:00
pub struct SayHiMiddleware<S> {
service: S,
}
impl<S, B> Service<ServiceRequest> for SayHiMiddleware<S>
2019-03-10 19:19:50 -07:00
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
2019-03-10 19:19:50 -07:00
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
2019-04-25 11:19:21 -07:00
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
2019-03-10 19:19:50 -07:00
dev::forward_ready!(service);
2018-07-09 21:36:03 +02:00
fn call(&self, req: ServiceRequest) -> Self::Future {
2019-03-10 19:19:50 -07:00
println!("Hi from start. You requested: {}", req.path());
2019-12-07 23:59:24 +06:00
let fut = self.service.call(req);
Box::pin(async move {
let res = fut.await?;
2019-03-10 19:19:50 -07:00
println!("Hi from response");
Ok(res)
2019-12-07 23:59:24 +06:00
})
2018-07-09 21:36:03 +02:00
}
2018-07-09 20:18:31 +02:00
}