1
0
mirror of https://github.com/actix/actix-website synced 2024-11-24 00:41:07 +01:00
actix-website/examples/middleware/src/main.rs
Ross 50c3e75bc3
Added documentation for from_fn and wrap in middleware page (#451)
* Added documentation for from_fn and wrap in middleware page

* Update docs/middleware.md

---------

Co-authored-by: Rob Ede <robjtede@icloud.com>
2024-09-11 13:51:39 +00:00

89 lines
2.2 KiB
Rust

pub mod default_headers;
pub mod errorhandler;
pub mod from_fn;
pub mod logger;
pub mod user_sessions;
pub mod wrap_fn;
// <simple>
use std::future::{ready, Ready};
use actix_web::{
dev::{forward_ready, 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
// `S` - type of the next service
// `B` - type of response's body
impl<S, B> Transform<S, ServiceRequest> for SayHi
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type InitError = ();
type Transform = SayHiMiddleware<S>;
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(SayHiMiddleware { service }))
}
}
pub struct SayHiMiddleware<S> {
service: S,
}
impl<S, B> Service<ServiceRequest> for SayHiMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
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)
})
}
}
// </simple>
#[actix_web::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer};
HttpServer::new(|| {
App::new().wrap(SayHi).service(
web::resource("/").to(|| async {
"Hello, middleware! Check the console where the server is run."
}),
)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}