1
0
mirror of https://github.com/actix/actix-website synced 2024-11-27 18:12:57 +01:00
actix-website/examples/middleware/src/main.rs

83 lines
2.2 KiB
Rust
Raw Normal View History

pub mod default_headers;
pub mod errorhandler;
pub mod logger;
pub mod user_sessions;
2019-06-26 08:59:20 +02:00
// <simple>
2019-06-17 22:57:57 +02:00
use actix_service::{Service, Transform};
2019-06-26 08:59:20 +02:00
use actix_web::{dev::ServiceRequest, dev::ServiceResponse, Error};
2019-06-17 22:57:57 +02:00
use futures::future::{ok, FutureResult};
use futures::{Future, Poll};
// 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<S, B> Transform<S> for SayHi
where
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Request = ServiceRequest;
type Response = ServiceResponse<B>;
type Error = Error;
type InitError = ();
type Transform = SayHiMiddleware<S>;
type Future = FutureResult<Self::Transform, Self::InitError>;
fn new_transform(&self, service: S) -> Self::Future {
ok(SayHiMiddleware { service })
}
}
pub struct SayHiMiddleware<S> {
service: S,
}
impl<S, B> Service for SayHiMiddleware<S>
where
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Request = ServiceRequest;
type Response = ServiceResponse<B>;
type Error = Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
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)
}))
}
}
2019-06-26 08:59:20 +02:00
// </simple>
2019-06-17 22:57:57 +02:00
fn main() {
2019-06-26 08:59:20 +02:00
use actix_web::{web, App, HttpServer};
HttpServer::new(|| {
App::new().wrap(SayHi).service(
web::resource("/")
.to(|| "Hello, middleware! Check the console where the server is run."),
)
})
.bind("127.0.0.1:8088")
.unwrap()
.run()
.unwrap();
2019-06-17 22:57:57 +02:00
}