http_type/request/
impl.rs

1use crate::*;
2
3/// Implements the `std::error::Error` trait for `RequestError`.
4impl std::error::Error for RequestError {}
5
6/// Implements the `Display` trait for `RequestError`, allowing it to be formatted as a string.
7impl Display for RequestError {
8    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9        match self {
10            Self::HttpRead(status) => write!(f, "Http read error [{}]", status.code()),
11            Self::GetTcpStream(status) => write!(f, "Failed to get tcp stream [{}]", status.code()),
12            Self::GetTlsStream(status) => write!(f, "Failed to get tls stream [{}]", status.code()),
13            Self::ReadConnection(status) => write!(f, "Connection read error [{}]", status.code()),
14            Self::RequestAborted(status) => write!(f, "Request aborted [{}]", status.code()),
15            Self::TlsStreamConnect(status) => {
16                write!(f, "Tls stream connection error [{}]", status.code())
17            }
18            Self::NeedOpenRedirect(status) => {
19                write!(f, "Open redirect required [{}]", status.code())
20            }
21            Self::MaxRedirectTimes(status) => {
22                write!(f, "Exceeded maximum redirect attempts [{}]", status.code())
23            }
24            Self::MethodsNotSupport(status) => {
25                write!(f, "Http method not supported [{}]", status.code())
26            }
27            Self::RedirectInvalidUrl(status) => {
28                write!(f, "Invalid redirect url [{}]", status.code())
29            }
30            Self::ClientDisconnected(status) => {
31                write!(f, "Client disconnected [{}]", status.code())
32            }
33            Self::RedirectUrlDeadLoop(status) => {
34                write!(f, "Redirect url dead loop detected [{}]", status.code())
35            }
36            Self::ClientClosedConnection(status) => {
37                write!(f, "Client closed connection [{}]", status.code())
38            }
39            Self::IncompleteWebSocketFrame(status) => write!(
40                f,
41                "WebSocket connection closed before a complete frame was received [{}]",
42                status.code()
43            ),
44            Self::RequestTooLong(status) => write!(f, "Request line too long [{}]", status.code()),
45            Self::PathTooLong(status) => write!(f, "Path too long [{}]", status.code()),
46            Self::QueryTooLong(status) => write!(f, "Query string too long [{}]", status.code()),
47            Self::HeaderLineTooLong(status) => {
48                write!(f, "Header line too long [{}]", status.code())
49            }
50            Self::TooManyHeaders(status) => write!(f, "Too many headers [{}]", status.code()),
51            Self::HeaderKeyTooLong(status) => write!(f, "Header key too long [{}]", status.code()),
52            Self::HeaderValueTooLong(status) => {
53                write!(f, "Header value too long [{}]", status.code())
54            }
55            Self::ContentLengthTooLarge(status) => {
56                write!(f, "Content length too large [{}]", status.code())
57            }
58            Self::InvalidContentLength(status) => {
59                write!(f, "Invalid content length [{}]", status.code())
60            }
61            Self::Unknown(status) => write!(f, "Unknown error occurred [{}]", status.code()),
62            Self::InvalidUrlScheme(status) => write!(f, "Invalid URL scheme [{}]", status.code()),
63            Self::InvalidUrlHost(status) => write!(f, "Invalid URL host [{}]", status.code()),
64            Self::InvalidUrlPort(status) => write!(f, "Invalid URL port [{}]", status.code()),
65            Self::InvalidUrlPath(status) => write!(f, "Invalid URL path [{}]", status.code()),
66            Self::InvalidUrlQuery(status) => write!(f, "Invalid URL query [{}]", status.code()),
67            Self::InvalidUrlFragment(status) => {
68                write!(f, "Invalid URL fragment [{}]", status.code())
69            }
70            Self::ReadTimeoutNotSet(status) => {
71                write!(f, "Failed to set read timeout [{}]", status.code())
72            }
73            Self::WriteTimeoutNotSet(status) => {
74                write!(f, "Failed to set write timeout [{}]", status.code())
75            }
76            Self::TcpConnectionFailed(status) => {
77                write!(f, "Tcp connection failed [{}]", status.code())
78            }
79            Self::TlsHandshakeFailed(status) => {
80                write!(f, "Tls handshake failed [{}]", status.code())
81            }
82            Self::TlsCertificateInvalid(status) => {
83                write!(f, "Tls certificate invalid [{}]", status.code())
84            }
85            Self::WebSocketFrameTooLarge(status) => {
86                write!(f, "WebSocket frame too large [{}]", status.code())
87            }
88            Self::WebSocketOpcodeUnsupported(status) => {
89                write!(f, "WebSocket opcode unsupported [{}]", status.code())
90            }
91            Self::WebSocketMaskMissing(status) => {
92                write!(f, "WebSocket mask missing [{}]", status.code())
93            }
94            Self::WebSocketPayloadCorrupted(status) => {
95                write!(f, "WebSocket payload corrupted [{}]", status.code())
96            }
97            Self::WebSocketInvalidUtf8(status) => {
98                write!(f, "WebSocket invalid UTF-8 [{}]", status.code())
99            }
100            Self::WebSocketInvalidCloseCode(status) => {
101                write!(f, "WebSocket invalid close code [{}]", status.code())
102            }
103            Self::WebSocketInvalidExtension(status) => {
104                write!(f, "WebSocket invalid extension [{}]", status.code())
105            }
106            Self::HttpRequestPartsInsufficient(status) => {
107                write!(f, "HTTP request parts insufficient [{}]", status.code())
108            }
109        }
110    }
111}
112
113impl RequestError {
114    /// Gets the HTTP status associated with this error.
115    ///
116    /// Returns the HttpStatus enum variant that corresponds to this error.
117    ///
118    /// # Arguments
119    ///
120    /// - `&self` - The RequestError instance.
121    ///
122    /// # Returns
123    ///
124    /// - `HttpStatus` - The HTTP status associated with this error.
125    #[inline(always)]
126    pub fn get_http_status(&self) -> HttpStatus {
127        match self {
128            Self::HttpRead(status) => *status,
129            Self::GetTcpStream(status) => *status,
130            Self::GetTlsStream(status) => *status,
131            Self::ReadConnection(status) => *status,
132            Self::RequestAborted(status) => *status,
133            Self::TlsStreamConnect(status) => *status,
134            Self::NeedOpenRedirect(status) => *status,
135            Self::MaxRedirectTimes(status) => *status,
136            Self::MethodsNotSupport(status) => *status,
137            Self::RedirectInvalidUrl(status) => *status,
138            Self::ClientDisconnected(status) => *status,
139            Self::RedirectUrlDeadLoop(status) => *status,
140            Self::ClientClosedConnection(status) => *status,
141            Self::IncompleteWebSocketFrame(status) => *status,
142            Self::RequestTooLong(status) => *status,
143            Self::PathTooLong(status) => *status,
144            Self::QueryTooLong(status) => *status,
145            Self::HeaderLineTooLong(status) => *status,
146            Self::TooManyHeaders(status) => *status,
147            Self::HeaderKeyTooLong(status) => *status,
148            Self::HeaderValueTooLong(status) => *status,
149            Self::ContentLengthTooLarge(status) => *status,
150            Self::InvalidContentLength(status) => *status,
151            Self::Unknown(status) => *status,
152            Self::InvalidUrlScheme(status) => *status,
153            Self::InvalidUrlHost(status) => *status,
154            Self::InvalidUrlPort(status) => *status,
155            Self::InvalidUrlPath(status) => *status,
156            Self::InvalidUrlQuery(status) => *status,
157            Self::InvalidUrlFragment(status) => *status,
158            Self::ReadTimeoutNotSet(status) => *status,
159            Self::WriteTimeoutNotSet(status) => *status,
160            Self::TcpConnectionFailed(status) => *status,
161            Self::TlsHandshakeFailed(status) => *status,
162            Self::TlsCertificateInvalid(status) => *status,
163            Self::WebSocketFrameTooLarge(status) => *status,
164            Self::WebSocketOpcodeUnsupported(status) => *status,
165            Self::WebSocketMaskMissing(status) => *status,
166            Self::WebSocketPayloadCorrupted(status) => *status,
167            Self::WebSocketInvalidUtf8(status) => *status,
168            Self::WebSocketInvalidCloseCode(status) => *status,
169            Self::WebSocketInvalidExtension(status) => *status,
170            Self::HttpRequestPartsInsufficient(status) => *status,
171        }
172    }
173
174    /// Gets the numeric HTTP status code associated with this error.
175    ///
176    /// Returns the numeric status code (e.g., 400, 404, 500) that corresponds to this error.
177    ///
178    /// # Arguments
179    ///
180    /// - `&self` - The RequestError instance.
181    ///
182    /// # Returns
183    ///
184    /// - `ResponseStatusCode` - The numeric HTTP status code.
185    pub fn get_http_status_code(&self) -> ResponseStatusCode {
186        self.get_http_status().code()
187    }
188}
189
190impl Default for RequestConfig {
191    /// Creates a `RequestConfig` with secure default values.
192    ///
193    /// # Returns
194    ///
195    /// - `RequestConfig` - A new config instance with secure defaults.
196    #[inline(always)]
197    fn default() -> Self {
198        Self {
199            buffer_size: DEFAULT_BUFFER_SIZE,
200            max_request_line_length: DEFAULT_MAX_REQUEST_LINE_LENGTH,
201            max_path_length: DEFAULT_MAX_PATH_LENGTH,
202            max_query_length: DEFAULT_MAX_QUERY_LENGTH,
203            max_header_line_length: DEFAULT_MAX_HEADER_LINE_LENGTH,
204            max_header_count: DEFAULT_MAX_HEADER_COUNT,
205            max_header_key_length: DEFAULT_MAX_HEADER_KEY_LENGTH,
206            max_header_value_length: DEFAULT_MAX_HEADER_VALUE_LENGTH,
207            max_body_size: DEFAULT_MAX_BODY_SIZE,
208            max_ws_frame_size: DEFAULT_MAX_WS_FRAME_SIZE,
209            max_ws_frames: DEFAULT_MAX_WS_FRAMES,
210            http_read_timeout_ms: DEFAULT_HTTP_READ_TIMEOUT_MS,
211            ws_read_timeout_ms: DEFAULT_WS_READ_TIMEOUT_MS,
212        }
213    }
214}
215
216impl RequestConfig {
217    /// Creates a new `RequestConfig` with default values.
218    ///
219    /// # Returns
220    ///
221    /// - `RequestConfig` - A new config instance with default values.
222    #[inline(always)]
223    pub fn new() -> Self {
224        Self::default()
225    }
226
227    /// Creates a config optimized for high-security environments.
228    ///
229    /// This configuration uses more restrictive limits to provide
230    /// maximum protection against various attacks.
231    ///
232    /// # Returns
233    ///
234    /// - `RequestConfig` - A new config with high-security settings.
235    #[inline(always)]
236    pub fn high_security() -> Self {
237        Self {
238            buffer_size: DEFAULT_HIGH_SECURITY_BUFFER_SIZE,
239            max_request_line_length: DEFAULT_HIGH_SECURITY_MAX_REQUEST_LINE_LENGTH,
240            max_path_length: DEFAULT_HIGH_SECURITY_MAX_PATH_LENGTH,
241            max_query_length: DEFAULT_HIGH_SECURITY_MAX_QUERY_LENGTH,
242            max_header_line_length: DEFAULT_HIGH_SECURITY_MAX_HEADER_LINE_LENGTH,
243            max_header_count: DEFAULT_HIGH_SECURITY_MAX_HEADER_COUNT,
244            max_header_key_length: DEFAULT_HIGH_SECURITY_MAX_HEADER_KEY_LENGTH,
245            max_header_value_length: DEFAULT_HIGH_SECURITY_MAX_HEADER_VALUE_LENGTH,
246            max_body_size: DEFAULT_HIGH_SECURITY_MAX_BODY_SIZE,
247            max_ws_frame_size: DEFAULT_HIGH_SECURITY_MAX_WS_FRAME_SIZE,
248            max_ws_frames: DEFAULT_HIGH_SECURITY_MAX_WS_FRAMES,
249            http_read_timeout_ms: DEFAULT_HIGH_SECURITY_HTTP_READ_TIMEOUT_MS,
250            ws_read_timeout_ms: DEFAULT_HIGH_SECURITY_WS_READ_TIMEOUT_MS,
251        }
252    }
253}
254
255/// Provides a default value for `Request`.
256///
257/// Returns a new `Request` instance with all fields initialized to their default values.
258impl Default for Request {
259    #[inline(always)]
260    fn default() -> Self {
261        Self {
262            method: Method::default(),
263            host: String::new(),
264            version: HttpVersion::default(),
265            path: String::new(),
266            querys: hash_map_xx_hash3_64(),
267            headers: hash_map_xx_hash3_64(),
268            body: Vec::new(),
269        }
270    }
271}
272
273impl Request {
274    /// Creates a new instance of `Request`.
275    ///
276    /// # Returns
277    ///
278    /// - `Request` - A new request instance with default values.
279    #[inline(always)]
280    pub fn new() -> Self {
281        Self::default()
282    }
283
284    /// Parses an HTTP request from a buffered TCP stream reader.
285    ///
286    /// Reads request line, headers and body from the stream and constructs a Request object.
287    ///
288    /// # Arguments
289    ///
290    /// - `&mut BufReader<&mut TcpStream>` - The buffered TCP stream reader.
291    /// - `&RequestConfig` - Configuration for security limits and buffer settings.
292    ///
293    /// # Returns
294    ///
295    /// - `Result<Request, RequestError>` - The parsed request or an error.
296    pub async fn http_from_reader(
297        reader: &mut BufReader<&mut TcpStream>,
298        config: &RequestConfig,
299    ) -> Result<Request, RequestError> {
300        let buffer_size: usize = *config.get_buffer_size();
301        let mut request_line: String = String::with_capacity(buffer_size);
302        let timeout_duration: Duration = Duration::from_millis(config.http_read_timeout_ms);
303        let bytes_read: usize = timeout(
304            timeout_duration,
305            AsyncBufReadExt::read_line(reader, &mut request_line),
306        )
307        .await
308        .map_err(|_| RequestError::ReadTimeoutNotSet(HttpStatus::RequestTimeout))?
309        .map_err(|_| RequestError::HttpRead(HttpStatus::BadRequest))?;
310        if bytes_read > config.max_request_line_length {
311            return Err(RequestError::RequestTooLong(HttpStatus::BadRequest));
312        }
313        let parts: Vec<&str> = request_line.split_whitespace().collect();
314        let parts_len: usize = parts.len();
315        if parts_len < 3 {
316            return Err(RequestError::HttpRequestPartsInsufficient(
317                HttpStatus::BadRequest,
318            ));
319        }
320        let full_path: &str = parts[1];
321        if full_path.len() > config.max_path_length {
322            return Err(RequestError::PathTooLong(HttpStatus::URITooLong));
323        }
324        let method: RequestMethod = parts[0]
325            .parse::<RequestMethod>()
326            .unwrap_or(Method::Unknown(parts[0].to_string()));
327        let full_path: RequestPath = full_path.to_string();
328        let version: RequestVersion = parts[2]
329            .parse::<RequestVersion>()
330            .unwrap_or(RequestVersion::Unknown(parts[2].to_string()));
331        let hash_index: Option<usize> = full_path.find(HASH);
332        let query_index: Option<usize> = full_path.find(QUERY);
333        let query_string: String = query_index.map_or_else(String::new, |i| {
334            let temp: &str = &full_path[i + 1..];
335            if hash_index.is_none() || hash_index.unwrap() <= i {
336                return temp.to_owned();
337            }
338            temp.split(HASH).next().unwrap_or_default().to_owned()
339        });
340        if query_string.len() > config.max_query_length {
341            return Err(RequestError::QueryTooLong(HttpStatus::URITooLong));
342        }
343        let querys: RequestQuerys = Self::parse_querys(&query_string);
344        let path: RequestPath = if let Some(i) = query_index.or(hash_index) {
345            full_path[..i].to_owned()
346        } else {
347            full_path.to_owned()
348        };
349        let mut headers: RequestHeaders = hash_map_xx_hash3_64();
350        let mut host: RequestHost = String::new();
351        let mut content_length: usize = 0;
352        let mut header_count: usize = 0;
353        loop {
354            let mut header_line: String = String::with_capacity(buffer_size);
355            let timeout_duration: Duration = Duration::from_millis(config.http_read_timeout_ms);
356            let bytes_read: usize = timeout(
357                timeout_duration,
358                AsyncBufReadExt::read_line(reader, &mut header_line),
359            )
360            .await
361            .map_err(|_| RequestError::ReadTimeoutNotSet(HttpStatus::RequestTimeout))?
362            .map_err(|_| RequestError::HttpRead(HttpStatus::BadRequest))?;
363            if bytes_read > config.max_header_line_length {
364                return Err(RequestError::HeaderLineTooLong(
365                    HttpStatus::RequestHeaderFieldsTooLarge,
366                ));
367            }
368            let header_line: &str = header_line.trim();
369            if header_line.is_empty() {
370                break;
371            }
372            header_count += 1;
373            if header_count > config.max_header_count {
374                return Err(RequestError::TooManyHeaders(
375                    HttpStatus::RequestHeaderFieldsTooLarge,
376                ));
377            }
378            if let Some((key_part, value_part)) = header_line.split_once(COLON) {
379                let key: String = key_part.trim().to_ascii_lowercase();
380                if key.is_empty() {
381                    continue;
382                }
383                if key.len() > config.max_header_key_length {
384                    return Err(RequestError::HeaderKeyTooLong(
385                        HttpStatus::RequestHeaderFieldsTooLarge,
386                    ));
387                }
388                let value: String = value_part.trim().to_string();
389                if value.len() > config.max_header_value_length {
390                    return Err(RequestError::HeaderValueTooLong(
391                        HttpStatus::RequestHeaderFieldsTooLarge,
392                    ));
393                }
394                if key == HOST {
395                    host = value.clone();
396                } else if key == CONTENT_LENGTH {
397                    match value.parse::<usize>() {
398                        Ok(length) => {
399                            if length > config.max_body_size {
400                                return Err(RequestError::ContentLengthTooLarge(
401                                    HttpStatus::PayloadTooLarge,
402                                ));
403                            }
404                            content_length = length;
405                        }
406                        Err(_) => {
407                            return Err(RequestError::InvalidContentLength(HttpStatus::BadRequest));
408                        }
409                    }
410                }
411                headers.entry(key).or_default().push_back(value);
412            }
413        }
414        let mut body: RequestBody = Vec::with_capacity(content_length);
415        if content_length > 0 {
416            body.resize(content_length, 0);
417            let timeout_duration: Duration = Duration::from_millis(config.http_read_timeout_ms);
418            timeout(
419                timeout_duration,
420                AsyncReadExt::read_exact(reader, &mut body),
421            )
422            .await
423            .map_err(|_| RequestError::ReadTimeoutNotSet(HttpStatus::RequestTimeout))?
424            .map_err(|_| RequestError::ReadConnection(HttpStatus::BadRequest))?;
425        }
426        Ok(Request {
427            method,
428            host,
429            version,
430            path,
431            querys,
432            headers,
433            body,
434        })
435    }
436
437    /// Parses an HTTP request from a TCP stream.
438    ///
439    /// Wraps the stream in a buffered reader and delegates to `http_from_reader`.
440    ///
441    /// # Arguments
442    ///
443    /// - `&ArcRwLock<TcpStream>` - The TCP stream to read from.
444    /// - `&RequestConfig` - Configuration for security limits and buffer settings.
445    ///
446    /// # Returns
447    ///
448    /// - `Result<Request, RequestError>` - The parsed request or an error.
449    pub async fn http_from_stream(
450        stream: &ArcRwLockStream,
451        config: &RequestConfig,
452    ) -> Result<Request, RequestError> {
453        let mut buf_stream: RwLockWriteGuard<'_, TcpStream> = stream.write().await;
454        let mut reader: BufReader<&mut TcpStream> = BufReader::new(&mut buf_stream);
455        Self::http_from_reader(&mut reader, config).await
456    }
457
458    /// Parses a WebSocket request from a TCP stream.
459    ///
460    /// Wraps the stream in a buffered reader and delegates to `ws_from_reader`.
461    ///
462    /// # Arguments
463    ///
464    /// - `&ArcRwLock<TcpStream>` - The TCP stream to read from.
465    /// - `&RequestConfig` - Configuration for security limits and buffer settings.
466    ///
467    /// # Returns
468    ///
469    /// - `Result<Request, RequestError>` - The parsed WebSocket request or an error.
470    pub async fn ws_from_stream(
471        &mut self,
472        stream: &ArcRwLockStream,
473        config: &RequestConfig,
474    ) -> Result<Request, RequestError> {
475        let mut buf_stream: RwLockWriteGuard<'_, TcpStream> = stream.write().await;
476        let mut reader: BufReader<&mut TcpStream> = BufReader::new(&mut buf_stream);
477        self.ws_from_reader(&mut reader, config).await
478    }
479
480    /// Parses a WebSocket request from a buffered TCP stream.
481    ///
482    /// Handles WebSocket frames including text, binary, ping, pong and close frames.
483    /// Assembles the request body from frame payload data.
484    ///
485    /// # Arguments
486    ///
487    /// - `&mut BufReader<&mut TcpStream>` - The buffered TCP stream reader.
488    /// - `&RequestConfig` - Configuration for security limits and buffer settings.
489    ///
490    /// # Returns
491    ///
492    /// - `Result<Request, RequestError>` - The parsed WebSocket request or an error.
493    pub async fn ws_from_reader(
494        &mut self,
495        reader: &mut BufReader<&mut TcpStream>,
496        config: &RequestConfig,
497    ) -> Result<Request, RequestError> {
498        let buffer_size: usize = *config.get_buffer_size();
499        let mut dynamic_buffer: Vec<u8> = Vec::with_capacity(buffer_size);
500        let temp_buffer_size: usize = buffer_size;
501        let mut temp_buffer: Vec<u8> = vec![0; temp_buffer_size];
502        let mut full_frame: Vec<u8> = Vec::with_capacity(config.max_ws_frame_size);
503        let mut frame_count: usize = 0;
504        loop {
505            let timeout_duration: Duration = Duration::from_millis(config.ws_read_timeout_ms);
506            let len: usize = match timeout(timeout_duration, reader.read(&mut temp_buffer)).await {
507                Ok(result) => match result {
508                    Ok(len) => len,
509                    Err(err) => {
510                        if err.kind() == ErrorKind::ConnectionReset
511                            || err.kind() == ErrorKind::ConnectionAborted
512                        {
513                            return Err(RequestError::ClientDisconnected(HttpStatus::BadRequest));
514                        }
515                        return Err(RequestError::Unknown(HttpStatus::InternalServerError));
516                    }
517                },
518                Err(_) => {
519                    return Err(RequestError::ReadTimeoutNotSet(HttpStatus::RequestTimeout));
520                }
521            };
522            if len == 0 {
523                return Err(RequestError::IncompleteWebSocketFrame(
524                    HttpStatus::BadRequest,
525                ));
526            }
527            dynamic_buffer.extend_from_slice(&temp_buffer[..len]);
528            while let Some((frame, consumed)) = WebSocketFrame::decode_ws_frame(&dynamic_buffer) {
529                dynamic_buffer.drain(0..consumed);
530                frame_count += 1;
531                if frame_count > config.max_ws_frames {
532                    return Err(RequestError::TooManyHeaders(
533                        HttpStatus::RequestHeaderFieldsTooLarge,
534                    ));
535                }
536                match frame.get_opcode() {
537                    WebSocketOpcode::Close => {
538                        return Err(RequestError::ClientClosedConnection(HttpStatus::BadRequest));
539                    }
540                    WebSocketOpcode::Ping | WebSocketOpcode::Pong => {
541                        continue;
542                    }
543                    WebSocketOpcode::Text | WebSocketOpcode::Binary => {
544                        let payload_data: &[u8] = frame.get_payload_data();
545                        if payload_data.len() > config.max_ws_frame_size {
546                            return Err(RequestError::WebSocketFrameTooLarge(
547                                HttpStatus::PayloadTooLarge,
548                            ));
549                        }
550                        if full_frame.len() + payload_data.len() > config.max_ws_frame_size {
551                            return Err(RequestError::WebSocketFrameTooLarge(
552                                HttpStatus::PayloadTooLarge,
553                            ));
554                        }
555                        full_frame.extend_from_slice(payload_data);
556                        if *frame.get_fin() {
557                            let mut request: Request = self.clone();
558                            request.body = full_frame;
559                            return Ok(request);
560                        }
561                    }
562                    _ => {
563                        return Err(RequestError::WebSocketOpcodeUnsupported(
564                            HttpStatus::NotImplemented,
565                        ));
566                    }
567                }
568            }
569        }
570    }
571
572    /// Parses a query string as_ref key-value pairs.
573    ///
574    /// Expects format "key1=value1&key2=value2". Empty values are allowed.
575    ///
576    /// # Arguments
577    ///
578    /// - `&str` - The query string to parse.
579    ///
580    /// # Returns
581    ///
582    /// - `HashMap<String, String>` - The parsed query parameters.
583    fn parse_querys<Q>(query: Q) -> RequestQuerys
584    where
585        Q: AsRef<str>,
586    {
587        let mut query_map: RequestQuerys = hash_map_xx_hash3_64();
588        for pair in query.as_ref().split(AND) {
589            if let Some((key, value)) = pair.split_once(EQUAL) {
590                if !key.is_empty() {
591                    query_map.insert(key.to_string(), value.to_string());
592                }
593            } else if !pair.is_empty() {
594                query_map.insert(pair.to_string(), String::new());
595            }
596        }
597        query_map
598    }
599
600    /// Tries to get a query parameter value by key.
601    ///
602    /// The key type must implement AsRef<str> conversion.
603    ///
604    /// # Arguments
605    ///
606    /// - `AsRef<str>` - The query parameter key (implements AsRef<str>).
607    ///
608    /// # Returns
609    ///
610    /// - `Option<RequestQuerysValue>` - The parameter value if exists.
611    #[inline(always)]
612    pub fn try_get_query<K>(&self, key: K) -> Option<RequestQuerysValue>
613    where
614        K: AsRef<str>,
615    {
616        self.querys.get(key.as_ref()).cloned()
617    }
618
619    /// Gets a query parameter value by key.
620    ///
621    /// The key type must implement AsRef<str> conversion.
622    ///
623    /// # Arguments
624    ///
625    /// - `AsRef<str>` - The query parameter key (implements AsRef<str>).
626    ///
627    /// # Returns
628    ///
629    /// - `RequestQuerysValue` - The parameter value if exists.
630    ///
631    /// # Panics
632    ///
633    /// This function will panic if the query parameter key is not found.
634    #[inline(always)]
635    pub fn get_query<K>(&self, key: K) -> RequestQuerysValue
636    where
637        K: AsRef<str>,
638    {
639        self.try_get_query(key).unwrap()
640    }
641
642    /// Tries to retrieve the value of a request header by its key.
643    ///
644    /// # Arguments
645    ///
646    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
647    ///
648    /// # Returns
649    ///
650    /// - `Option<RequestHeadersValue>` - The optional header values.
651    #[inline(always)]
652    pub fn try_get_header<K>(&self, key: K) -> Option<RequestHeadersValue>
653    where
654        K: AsRef<str>,
655    {
656        self.headers.get(key.as_ref()).cloned()
657    }
658
659    /// Retrieves the value of a request header by its key.
660    ///
661    /// # Arguments
662    ///
663    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
664    ///
665    /// # Returns
666    ///
667    /// - `RequestHeadersValue` - The optional header values.
668    ///
669    /// # Panics
670    ///
671    /// This function will panic if the header key is not found.
672    #[inline(always)]
673    pub fn get_header<K>(&self, key: K) -> RequestHeadersValue
674    where
675        K: AsRef<str>,
676    {
677        self.try_get_header(key).unwrap()
678    }
679
680    /// Tries to retrieve the first value of a request header by its key.
681    ///
682    /// # Arguments
683    ///
684    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
685    ///
686    /// # Returns
687    ///
688    /// - `Option<RequestHeadersValueItem>` - The first header value if exists.
689    #[inline(always)]
690    pub fn try_get_header_front<K>(&self, key: K) -> Option<RequestHeadersValueItem>
691    where
692        K: AsRef<str>,
693    {
694        self.headers
695            .get(key.as_ref())
696            .and_then(|values| values.front().cloned())
697    }
698
699    /// Retrieves the first value of a request header by its key.
700    ///
701    /// # Arguments
702    ///
703    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
704    ///
705    /// # Returns
706    ///
707    /// - `RequestHeadersValueItem` - The first header value if exists.
708    ///
709    /// # Panics
710    ///
711    /// This function will panic if the header key is not found.
712    #[inline(always)]
713    pub fn get_header_front<K>(&self, key: K) -> RequestHeadersValueItem
714    where
715        K: AsRef<str>,
716    {
717        self.try_get_header_front(key).unwrap()
718    }
719
720    /// Tries to retrieve the last value of a request header by its key.
721    ///
722    /// # Arguments
723    ///
724    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
725    ///
726    /// # Returns
727    ///
728    /// - `Option<RequestHeadersValueItem>` - The last header value if exists.
729    #[inline(always)]
730    pub fn try_get_header_back<K>(&self, key: K) -> Option<RequestHeadersValueItem>
731    where
732        K: AsRef<str>,
733    {
734        self.headers
735            .get(key.as_ref())
736            .and_then(|values| values.back().cloned())
737    }
738
739    /// Retrieves the last value of a request header by its key.
740    ///
741    /// # Arguments
742    ///
743    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
744    ///
745    /// # Returns
746    ///
747    /// - `RequestHeadersValueItem` - The last header value if exists.
748    ///
749    /// # Panics
750    ///
751    /// This function will panic if the header key is not found.
752    #[inline(always)]
753    pub fn get_header_back<K>(&self, key: K) -> RequestHeadersValueItem
754    where
755        K: AsRef<str>,
756    {
757        self.try_get_header_back(key).unwrap()
758    }
759
760    /// Tries to retrieve the number of values for a specific header.
761    ///
762    /// # Arguments
763    ///
764    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
765    ///
766    /// # Returns
767    ///
768    /// - `Option<usize>` - The count of values for the header if exists.
769    #[inline(always)]
770    pub fn try_get_header_length<K>(&self, key: K) -> Option<usize>
771    where
772        K: AsRef<str>,
773    {
774        self.headers.get(key.as_ref()).map(|values| values.len())
775    }
776
777    /// Retrieves the number of values for a specific header.
778    ///
779    /// # Arguments
780    ///
781    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
782    ///
783    /// # Returns
784    ///
785    /// - `usize` - The count of values for the header.
786    ///
787    /// # Panics
788    ///
789    /// This function will panic if the header key is not found.
790    #[inline(always)]
791    pub fn get_header_length<K>(&self, key: K) -> usize
792    where
793        K: AsRef<str>,
794    {
795        self.try_get_header_length(key).unwrap()
796    }
797
798    /// Retrieves the total number of header values across all headers.
799    ///
800    /// # Returns
801    ///
802    /// - `usize` - The total count of all header values.
803    #[inline(always)]
804    pub fn get_headers_values_length(&self) -> usize {
805        self.headers.values().map(|values| values.len()).sum()
806    }
807
808    /// Retrieves the number of unique headers.
809    ///
810    /// # Returns
811    ///
812    /// - `usize` - The count of unique header keys.
813    #[inline(always)]
814    pub fn get_headers_length(&self) -> usize {
815        self.headers.len()
816    }
817
818    /// Checks if a specific header exists.
819    ///
820    /// # Arguments
821    ///
822    /// - `AsRef<str>` - The header key to check (must implement AsRef<str>).
823    ///
824    /// # Returns
825    ///
826    /// - `bool` - Whether the header exists.
827    #[inline(always)]
828    pub fn has_header<K>(&self, key: K) -> bool
829    where
830        K: AsRef<str>,
831    {
832        self.headers.contains_key(key.as_ref())
833    }
834
835    /// Checks if a header contains a specific value.
836    ///
837    /// # Arguments
838    ///
839    /// - `AsRef<str>` - The header key to check (must implement AsRef<str>).
840    /// - `AsRef<str>` - The value to search for (must implement AsRef<str>).
841    ///
842    /// # Returns
843    ///
844    /// - `bool` - Whether the header contains the value.
845    #[inline(always)]
846    pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
847    where
848        K: AsRef<str>,
849        V: AsRef<str>,
850    {
851        if let Some(values) = self.headers.get(key.as_ref()) {
852            values.contains(&value.as_ref().to_owned())
853        } else {
854            false
855        }
856    }
857
858    /// Retrieves the body content of the request as a UTF-8 encoded string.
859    ///
860    /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` as_ref a string.
861    /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character ().
862    ///
863    /// # Returns
864    ///
865    /// - `String` - The body content as a string.
866    #[inline(always)]
867    pub fn get_body_string(&self) -> String {
868        String::from_utf8_lossy(self.get_body()).into_owned()
869    }
870
871    /// Deserializes the body content of the request as_ref a specified type `T`.
872    ///
873    /// This method first retrieves the body content as a byte slice using `self.get_body()`.
874    /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
875    ///
876    /// # Arguments
877    ///
878    /// - `DeserializeOwned` - The target type to deserialize as_ref (must implement DeserializeOwned).
879    ///
880    /// # Returns
881    ///
882    /// - `Result<T, serde_json::Error>` - The deserialization result.
883    pub fn try_get_body_json<T>(&self) -> Result<T, serde_json::Error>
884    where
885        T: DeserializeOwned,
886    {
887        serde_json::from_slice(self.get_body())
888    }
889
890    /// Deserializes the body content of the request as_ref a specified type `T`.
891    ///
892    /// This method first retrieves the body content as a byte slice using `self.get_body()`.
893    /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
894    ///
895    /// # Arguments
896    ///
897    /// - `DeserializeOwned` - The target type to deserialize as_ref (must implement DeserializeOwned).
898    ///
899    /// # Returns
900    ///
901    /// - `T` - The deserialized body content.
902    ///
903    /// # Panics
904    ///
905    /// This function will panic if the deserialization fails.
906    pub fn get_body_json<T>(&self) -> T
907    where
908        T: DeserializeOwned,
909    {
910        self.try_get_body_json().unwrap()
911    }
912
913    /// Converts the request to a formatted string representation.
914    ///
915    /// This method provides a human-readable summary of the request, including its method,
916    /// host, version, path, query parameters, headers, and body information.
917    ///
918    /// # Returns
919    ///
920    /// - `String` - The formatted request details.
921    #[inline(always)]
922    pub fn get_string(&self) -> String {
923        let body: &Vec<u8> = self.get_body();
924        let body_type: &'static str = if std::str::from_utf8(body).is_ok() {
925            PLAIN
926        } else {
927            BINARY
928        };
929        format!(
930            "[Request] => [method]: {}; [host]: {}; [version]: {}; [path]: {}; [querys]: {:?}; [headers]: {:?}; [body]: {} bytes {};",
931            self.get_method(),
932            self.get_host(),
933            self.get_version(),
934            self.get_path(),
935            self.get_querys(),
936            self.get_headers(),
937            body.len(),
938            body_type
939        )
940    }
941
942    /// Retrieves the upgrade type from the request headers.
943    ///
944    /// This method looks for the `UPGRADE` header and attempts to parse its value
945    /// as_ref an `UpgradeType`. If the header is missing or the value is invalid,
946    /// it returns the default `UpgradeType`.
947    ///
948    /// # Returns
949    ///
950    /// - `UpgradeType` - The parsed upgrade type.
951    #[inline(always)]
952    pub fn get_upgrade_type(&self) -> UpgradeType {
953        let upgrade_type: UpgradeType = self
954            .try_get_header_back(UPGRADE)
955            .and_then(|data| data.parse::<UpgradeType>().ok())
956            .unwrap_or_default();
957        upgrade_type
958    }
959
960    /// Checks whether the WebSocket upgrade is enabled for this request.
961    ///
962    /// This method determines if the `UPGRADE` header indicates a WebSocket connection.
963    ///
964    /// # Returns
965    ///
966    /// - `bool` - Whether WebSocket upgrade is enabled.
967    #[inline(always)]
968    pub fn is_ws(&self) -> bool {
969        self.get_upgrade_type().is_ws()
970    }
971
972    /// Checks if the current upgrade type is HTTP/2 cleartext (h2c).
973    ///
974    /// # Returns
975    ///
976    /// - `bool` - Whether the upgrade type is h2c.
977    #[inline(always)]
978    pub fn is_h2c(&self) -> bool {
979        self.get_upgrade_type().is_h2c()
980    }
981
982    /// Checks if the current upgrade type is TLS (any version).
983    ///
984    /// # Returns
985    ///
986    /// - `bool` - Whether the upgrade type is TLS.
987    #[inline(always)]
988    pub fn is_tls(&self) -> bool {
989        self.get_upgrade_type().is_tls()
990    }
991
992    /// Checks whether the upgrade type is unknown.
993    ///
994    /// # Returns
995    ///
996    /// - `bool` - Whether the upgrade type is unknown.
997    #[inline(always)]
998    pub fn is_unknown_upgrade(&self) -> bool {
999        self.get_upgrade_type().is_unknown()
1000    }
1001
1002    /// Checks if the HTTP version is HTTP/1.1 or higher.
1003    ///
1004    /// # Returns
1005    ///
1006    /// - `bool` - Whether the version is HTTP/1.1 or higher.
1007    #[inline(always)]
1008    pub fn is_http1_1_or_higher(&self) -> bool {
1009        self.get_version().is_http1_1_or_higher()
1010    }
1011
1012    /// Checks whether the HTTP version is HTTP/0.9.
1013    ///
1014    /// # Returns
1015    ///
1016    /// - `bool` - Whether the version is HTTP/0.9.
1017    #[inline(always)]
1018    pub fn is_http0_9(&self) -> bool {
1019        self.get_version().is_http0_9()
1020    }
1021
1022    /// Checks whether the HTTP version is HTTP/1.0.
1023    ///
1024    /// # Returns
1025    ///
1026    /// - `bool` - Whether the version is HTTP/1.0.
1027    #[inline(always)]
1028    pub fn is_http1_0(&self) -> bool {
1029        self.get_version().is_http1_0()
1030    }
1031
1032    /// Checks whether the HTTP version is HTTP/1.1.
1033    ///
1034    /// # Returns
1035    ///
1036    /// - `bool` - Whether the version is HTTP/1.1.
1037    #[inline(always)]
1038    pub fn is_http1_1(&self) -> bool {
1039        self.get_version().is_http1_1()
1040    }
1041
1042    /// Checks whether the HTTP version is HTTP/2.
1043    ///
1044    /// # Returns
1045    ///
1046    /// - `bool` - Whether the version is HTTP/2.
1047    #[inline(always)]
1048    pub fn is_http2(&self) -> bool {
1049        self.get_version().is_http2()
1050    }
1051
1052    /// Checks whether the HTTP version is HTTP/3.
1053    ///
1054    /// # Returns
1055    ///
1056    /// - `bool` - Whether the version is HTTP/3.
1057    #[inline(always)]
1058    pub fn is_http3(&self) -> bool {
1059        self.get_version().is_http3()
1060    }
1061
1062    /// Checks whether the HTTP version is unknown.
1063    ///
1064    /// # Returns
1065    ///
1066    /// - `bool` - Whether the version is unknown.
1067    #[inline(always)]
1068    pub fn is_unknown_version(&self) -> bool {
1069        self.get_version().is_unknown()
1070    }
1071
1072    /// Checks whether the version belongs to the HTTP family.
1073    ///
1074    /// # Returns
1075    ///
1076    /// - `bool` - Whether the version is HTTP.
1077    #[inline(always)]
1078    pub fn is_http(&self) -> bool {
1079        self.get_version().is_http()
1080    }
1081
1082    /// Checks whether the request method is GET.
1083    ///
1084    /// # Returns
1085    ///
1086    /// - `bool` - Whether the method is GET.
1087    #[inline(always)]
1088    pub fn is_get(&self) -> bool {
1089        self.get_method().is_get()
1090    }
1091
1092    /// Checks whether the request method is POST.
1093    ///
1094    /// # Returns
1095    ///
1096    /// - `bool` - Whether the method is POST.
1097    #[inline(always)]
1098    pub fn is_post(&self) -> bool {
1099        self.get_method().is_post()
1100    }
1101
1102    /// Checks whether the request method is PUT.
1103    ///
1104    /// # Returns
1105    ///
1106    /// - `bool` - Whether the method is PUT.
1107    #[inline(always)]
1108    pub fn is_put(&self) -> bool {
1109        self.get_method().is_put()
1110    }
1111
1112    /// Checks whether the request method is DELETE.
1113    ///
1114    /// # Returns
1115    ///
1116    /// - `bool` - Whether the method is DELETE.
1117    #[inline(always)]
1118    pub fn is_delete(&self) -> bool {
1119        self.get_method().is_delete()
1120    }
1121
1122    /// Checks whether the request method is PATCH.
1123    ///
1124    /// # Returns
1125    ///
1126    /// - `bool` - Whether the method is PATCH.
1127    #[inline(always)]
1128    pub fn is_patch(&self) -> bool {
1129        self.get_method().is_patch()
1130    }
1131
1132    /// Checks whether the request method is HEAD.
1133    ///
1134    /// # Returns
1135    ///
1136    /// - `bool` - Whether the method is HEAD.
1137    #[inline(always)]
1138    pub fn is_head(&self) -> bool {
1139        self.get_method().is_head()
1140    }
1141
1142    /// Checks whether the request method is OPTIONS.
1143    ///
1144    /// # Returns
1145    ///
1146    /// - `bool` - Whether the method is OPTIONS.
1147    #[inline(always)]
1148    pub fn is_options(&self) -> bool {
1149        self.get_method().is_options()
1150    }
1151
1152    /// Checks whether the request method is CONNECT.
1153    ///
1154    /// # Returns
1155    ///
1156    /// - `bool` - Whether the method is CONNECT.
1157    #[inline(always)]
1158    pub fn is_connect(&self) -> bool {
1159        self.get_method().is_connect()
1160    }
1161
1162    /// Checks whether the request method is TRACE.
1163    ///
1164    /// # Returns
1165    ///
1166    /// - `bool` - Whether the method is TRACE.
1167    #[inline(always)]
1168    pub fn is_trace(&self) -> bool {
1169        self.get_method().is_trace()
1170    }
1171
1172    /// Checks whether the request method is UNKNOWN.
1173    ///
1174    /// # Returns
1175    ///
1176    /// - `bool` - Whether the method is UNKNOWN.
1177    #[inline(always)]
1178    pub fn is_unknown_method(&self) -> bool {
1179        self.get_method().is_unknown()
1180    }
1181
1182    /// Determines if a keep-alive connection should be enabled for this request.
1183    ///
1184    /// This function checks the `Connection` header and the HTTP version to determine
1185    /// if keep-alive should be enabled. The logic is as follows:
1186    ///
1187    /// 1. If the `Connection` header exists:
1188    ///    - Returns `true` if the header value is "keep-alive" (case-insensitive).
1189    ///    - Returns `false` if the header value is "close" (case-insensitive).
1190    /// 2. If no `Connection` header is present:
1191    ///    - Returns `true` if the HTTP version is 1.1 or higher.
1192    ///    - Returns `false` otherwise.
1193    ///
1194    /// # Returns
1195    ///
1196    /// - `bool` - Whether keep-alive should be enabled.
1197    #[inline(always)]
1198    pub fn is_enable_keep_alive(&self) -> bool {
1199        if let Some(connection_value) = self.try_get_header_back(CONNECTION) {
1200            if connection_value.eq_ignore_ascii_case(KEEP_ALIVE) {
1201                return true;
1202            } else if connection_value.eq_ignore_ascii_case(CLOSE) {
1203                return self.is_ws();
1204            }
1205        }
1206        self.is_http1_1_or_higher() || self.is_ws()
1207    }
1208
1209    /// Determines if keep-alive should be disabled for this request.
1210    ///
1211    /// # Returns
1212    ///
1213    /// - `bool` - Whether keep-alive should be disabled.
1214    #[inline(always)]
1215    pub fn is_disable_keep_alive(&self) -> bool {
1216        !self.is_enable_keep_alive()
1217    }
1218}