Skip to main content

this_env/middleware/actix/
env_request_parser.rs

1//this.env/crate/src/middleware/actix/env_request_parser.rs
2// by suiGn
3// Module for parsing Actix `HttpRequest` into `EnvRequest`
4// This module provides a function to convert Actix's `HttpRequest` into an internal
5// `EnvRequest` enum, which is used for environment analysis and routing.
6// It handles both HTTP and WebSocket requests, extracting relevant metadata such as headers,
7// method, path, and IP address. This allows the `this.env` framework to standardize
8// incoming requests across different protocols and frameworks, making it easier to implement
9// environment recognition, routing, and analytics.
10// This module is designed to be extensible, allowing for future ingress types to be added as
11use actix_web::HttpRequest;
12use crate::middleware::env_request::{EnvRequest, EnvRequestHttp, EnvRequestWs};
13use std::collections::HashMap;
14/// Parses an incoming Actix `HttpRequest` into an `EnvRequest`
15/// recognized by `this.env`.
16///
17/// This function standardizes different request types (e.g., HTTP vs WebSocket)
18/// into an internal `EnvRequest` enum used for environment analysis and routing.
19///
20/// # Arguments
21///
22/// * `req` - A reference to the incoming `HttpRequest`
23///
24/// # Returns
25///
26/// * `Option<EnvRequest>` - Returns an `EnvRequest` variant if parsing succeeds,
27///                          or `None` if not recognized.
28pub fn parse_env_request(req: &HttpRequest) -> Option<EnvRequest> {
29    //log::debug!("this.env parser: entering parser fn");
30    let mut headers = HashMap::new();
31    for (key, value) in req.headers().iter() {
32        if let Ok(val) = value.to_str() {
33            headers.insert(key.to_string(), val.to_string());
34        }
35    }
36
37    let host = req
38        .headers()
39        .get("host")
40        .and_then(|v| v.to_str().ok())
41        .unwrap_or_default()
42        .to_string();
43    let ip = req.connection_info().realip_remote_addr().map(|s| s.to_string());
44    let method = req.method().to_string();
45    let path = req.path().to_string();
46    let is_ws = req
47        .headers()
48        .get("upgrade")
49        .and_then(|v| v.to_str().ok())
50        .map(|v| v.eq_ignore_ascii_case("websocket"))
51        .unwrap_or(false);
52
53    if is_ws {
54        log::debug!("this.env parser: websocket request parsed");
55        Some(EnvRequest::Ws(EnvRequestWs {
56            host,
57            ip,
58            headers,
59            payload: None,
60        }))
61    } else {
62        log::debug!("this.env parser: http request parsed");
63        Some(EnvRequest::Http(EnvRequestHttp {
64            host,
65            ip,
66            method,
67            path,
68            headers,
69        }))
70    }
71}