rush_sync_server/server/
middleware.rs

1// =====================================================
2// FILE: src/server/middleware.rs - CUSTOM MIDDLEWARE
3// =====================================================
4
5use crate::server::ServerInfo;
6use actix_web::{
7    dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
8    Error, HttpMessage,
9};
10use futures::future::{ready, Ready};
11use std::sync::{Arc, Mutex};
12
13/// Middleware um Server-Info in Requests verfügbar zu machen
14pub struct ServerInfoMiddleware {
15    server_info: Arc<Mutex<ServerInfo>>,
16}
17
18impl ServerInfoMiddleware {
19    pub fn new(server_info: Arc<Mutex<ServerInfo>>) -> Self {
20        Self { server_info }
21    }
22}
23
24impl<S, B> Transform<S, ServiceRequest> for ServerInfoMiddleware
25where
26    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
27    S::Future: 'static,
28    B: 'static,
29{
30    type Response = ServiceResponse<B>;
31    type Error = Error;
32    type Transform = ServerInfoMiddlewareService<S>;
33    type InitError = ();
34    type Future = Ready<Result<Self::Transform, Self::InitError>>;
35
36    fn new_transform(&self, service: S) -> Self::Future {
37        ready(Ok(ServerInfoMiddlewareService {
38            service,
39            server_info: Arc::clone(&self.server_info),
40        }))
41    }
42}
43
44pub struct ServerInfoMiddlewareService<S> {
45    service: S,
46    server_info: Arc<Mutex<ServerInfo>>,
47}
48
49impl<S, B> Service<ServiceRequest> for ServerInfoMiddlewareService<S>
50where
51    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
52    S::Future: 'static,
53    B: 'static,
54{
55    type Response = ServiceResponse<B>;
56    type Error = Error;
57    type Future = S::Future;
58
59    forward_ready!(service);
60
61    fn call(&self, req: ServiceRequest) -> Self::Future {
62        // Server-Info in Request Extensions speichern
63        req.extensions_mut().insert(Arc::clone(&self.server_info));
64
65        // Request weiterleiten
66        self.service.call(req)
67    }
68}