1
0
mirror of https://github.com/actix/examples synced 2024-12-03 18:22:14 +01:00
examples/middleware/src/simple.rs

61 lines
1.8 KiB
Rust
Raw Normal View History

2019-03-11 03:19:50 +01:00
use actix_service::{Service, Transform};
2019-04-25 20:19:21 +02:00
use actix_web::{dev::ServiceRequest, dev::ServiceResponse, Error};
2019-03-11 03:19:50 +01:00
use futures::future::{ok, FutureResult};
use futures::{Future, Poll};
2018-07-09 20:18:31 +02:00
2019-06-06 23:20:25 +02:00
// There are two steps in middleware processing.
// 1. Middleware initialization, middleware factory gets called with
2019-03-11 03:19:50 +01:00
// next service in chain as parameter.
2019-06-06 23:20:25 +02:00
// 2. Middleware's call method gets called with normal request.
2018-07-09 20:18:31 +02:00
pub struct SayHi;
2019-03-11 03:19:50 +01:00
// Middleware factory is `Transform` trait from actix-service crate
// `S` - type of the next service
// `B` - type of response's body
2019-04-14 19:34:41 +02:00
impl<S, B> Transform<S> for SayHi
2019-03-11 03:19:50 +01:00
where
2019-04-25 20:19:21 +02:00
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
2019-03-11 03:19:50 +01:00
S::Future: 'static,
B: 'static,
{
2019-04-14 19:34:41 +02:00
type Request = ServiceRequest;
2019-03-11 03:19:50 +01:00
type Response = ServiceResponse<B>;
2019-04-25 20:19:21 +02:00
type Error = Error;
2019-03-11 03:19:50 +01:00
type InitError = ();
type Transform = SayHiMiddleware<S>;
type Future = FutureResult<Self::Transform, Self::InitError>;
fn new_transform(&self, service: S) -> Self::Future {
ok(SayHiMiddleware { service })
2018-07-09 20:18:31 +02:00
}
2019-03-11 03:19:50 +01:00
}
2018-07-09 21:36:03 +02:00
2019-03-11 03:19:50 +01:00
pub struct SayHiMiddleware<S> {
service: S,
}
2019-04-14 19:34:41 +02:00
impl<S, B> Service for SayHiMiddleware<S>
2019-03-11 03:19:50 +01:00
where
2019-04-25 20:19:21 +02:00
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
2019-03-11 03:19:50 +01:00
S::Future: 'static,
B: 'static,
{
2019-04-14 19:34:41 +02:00
type Request = ServiceRequest;
2019-03-11 03:19:50 +01:00
type Response = ServiceResponse<B>;
2019-04-25 20:19:21 +02:00
type Error = Error;
2019-09-04 17:04:57 +02:00
type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
2019-03-11 03:19:50 +01:00
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready()
2018-07-09 21:36:03 +02:00
}
2019-04-14 19:34:41 +02:00
fn call(&mut self, req: ServiceRequest) -> Self::Future {
2019-03-11 03:19:50 +01:00
println!("Hi from start. You requested: {}", req.path());
Box::new(self.service.call(req).and_then(|res| {
println!("Hi from response");
Ok(res)
}))
2018-07-09 21:36:03 +02:00
}
2018-07-09 20:18:31 +02:00
}