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 TCP stream.
285    ///
286    /// Wraps the stream in a buffered reader and delegates to `http_from_reader`.
287    ///
288    /// # Arguments
289    ///
290    /// - `&ArcRwLock<TcpStream>` - The TCP stream to read from.
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_stream(
297        stream: &ArcRwLockStream,
298        config: &RequestConfig,
299    ) -> Result<Request, RequestError> {
300        let mut buf_stream: RwLockWriteGuard<'_, TcpStream> = stream.write().await;
301        let buffer_size: usize = *config.get_buffer_size();
302        let reader: &mut BufReader<&mut TcpStream> =
303            &mut BufReader::with_capacity(buffer_size, &mut buf_stream);
304        let mut request_line: String = String::with_capacity(buffer_size);
305        let timeout_duration: Duration = Duration::from_millis(config.http_read_timeout_ms);
306        let bytes_read: usize = timeout(
307            timeout_duration,
308            AsyncBufReadExt::read_line(reader, &mut request_line),
309        )
310        .await
311        .map_err(|_| RequestError::ReadTimeoutNotSet(HttpStatus::RequestTimeout))?
312        .map_err(|_| RequestError::HttpRead(HttpStatus::BadRequest))?;
313        if bytes_read > config.max_request_line_length {
314            return Err(RequestError::RequestTooLong(HttpStatus::BadRequest));
315        }
316        let parts: Vec<&str> = request_line.split_whitespace().collect();
317        let parts_len: usize = parts.len();
318        if parts_len < 3 {
319            return Err(RequestError::HttpRequestPartsInsufficient(
320                HttpStatus::BadRequest,
321            ));
322        }
323        let full_path: &str = parts[1];
324        if full_path.len() > config.max_path_length {
325            return Err(RequestError::PathTooLong(HttpStatus::URITooLong));
326        }
327        let method: RequestMethod = parts[0]
328            .parse::<RequestMethod>()
329            .unwrap_or(Method::Unknown(parts[0].to_string()));
330        let full_path: RequestPath = full_path.to_string();
331        let version: RequestVersion = parts[2]
332            .parse::<RequestVersion>()
333            .unwrap_or(RequestVersion::Unknown(parts[2].to_string()));
334        let hash_index: Option<usize> = full_path.find(HASH);
335        let query_index: Option<usize> = full_path.find(QUERY);
336        let query_string: String = query_index.map_or_else(String::new, |i| {
337            let temp: &str = &full_path[i + 1..];
338            if hash_index.is_none() || hash_index.unwrap() <= i {
339                return temp.to_owned();
340            }
341            temp.split(HASH).next().unwrap_or_default().to_owned()
342        });
343        if query_string.len() > config.max_query_length {
344            return Err(RequestError::QueryTooLong(HttpStatus::URITooLong));
345        }
346        let querys: RequestQuerys = Self::parse_querys(&query_string);
347        let path: RequestPath = if let Some(i) = query_index.or(hash_index) {
348            full_path[..i].to_owned()
349        } else {
350            full_path.to_owned()
351        };
352        let mut headers: RequestHeaders = hash_map_xx_hash3_64();
353        let mut host: RequestHost = String::new();
354        let mut content_length: usize = 0;
355        let mut header_count: usize = 0;
356        loop {
357            let header_line: &mut String = &mut String::with_capacity(buffer_size);
358            let timeout_duration: Duration = Duration::from_millis(config.http_read_timeout_ms);
359            let bytes_read: usize = timeout(
360                timeout_duration,
361                AsyncBufReadExt::read_line(reader, header_line),
362            )
363            .await
364            .map_err(|_| RequestError::ReadTimeoutNotSet(HttpStatus::RequestTimeout))?
365            .map_err(|_| RequestError::HttpRead(HttpStatus::BadRequest))?;
366            if bytes_read > config.max_header_line_length {
367                return Err(RequestError::HeaderLineTooLong(
368                    HttpStatus::RequestHeaderFieldsTooLarge,
369                ));
370            }
371            let header_line: &str = header_line.trim();
372            if header_line.is_empty() {
373                break;
374            }
375            header_count += 1;
376            if header_count > config.max_header_count {
377                return Err(RequestError::TooManyHeaders(
378                    HttpStatus::RequestHeaderFieldsTooLarge,
379                ));
380            }
381            if let Some((key_part, value_part)) = header_line.split_once(COLON) {
382                let key: String = key_part.trim().to_ascii_lowercase();
383                if key.is_empty() {
384                    continue;
385                }
386                if key.len() > config.max_header_key_length {
387                    return Err(RequestError::HeaderKeyTooLong(
388                        HttpStatus::RequestHeaderFieldsTooLarge,
389                    ));
390                }
391                let value: String = value_part.trim().to_string();
392                if value.len() > config.max_header_value_length {
393                    return Err(RequestError::HeaderValueTooLong(
394                        HttpStatus::RequestHeaderFieldsTooLarge,
395                    ));
396                }
397                if key == HOST {
398                    host = value.clone();
399                } else if key == CONTENT_LENGTH {
400                    match value.parse::<usize>() {
401                        Ok(length) => {
402                            if length > config.max_body_size {
403                                return Err(RequestError::ContentLengthTooLarge(
404                                    HttpStatus::PayloadTooLarge,
405                                ));
406                            }
407                            content_length = length;
408                        }
409                        Err(_) => {
410                            return Err(RequestError::InvalidContentLength(HttpStatus::BadRequest));
411                        }
412                    }
413                }
414                headers.entry(key).or_default().push_back(value);
415            }
416        }
417        let mut body: RequestBody = Vec::with_capacity(content_length);
418        if content_length > 0 {
419            body.resize(content_length, 0);
420            let timeout_duration: Duration = Duration::from_millis(config.http_read_timeout_ms);
421            timeout(
422                timeout_duration,
423                AsyncReadExt::read_exact(reader, &mut body),
424            )
425            .await
426            .map_err(|_| RequestError::ReadTimeoutNotSet(HttpStatus::RequestTimeout))?
427            .map_err(|_| RequestError::ReadConnection(HttpStatus::BadRequest))?;
428        }
429        Ok(Request {
430            method,
431            host,
432            version,
433            path,
434            querys,
435            headers,
436            body,
437        })
438    }
439
440    /// Parses a WebSocket request from a TCP stream.
441    ///
442    /// Wraps the stream in a buffered reader and delegates to `ws_from_reader`.
443    ///
444    /// # Arguments
445    ///
446    /// - `&ArcRwLock<TcpStream>` - The TCP stream to read from.
447    /// - `&RequestConfig` - Configuration for security limits and buffer settings.
448    ///
449    /// # Returns
450    ///
451    /// - `Result<Request, RequestError>` - The parsed WebSocket request or an error.
452    pub async fn ws_from_stream(
453        &mut self,
454        stream: &ArcRwLockStream,
455        config: &RequestConfig,
456    ) -> Result<Request, RequestError> {
457        let buffer_size: usize = *config.get_buffer_size();
458        let mut dynamic_buffer: Vec<u8> = Vec::with_capacity(buffer_size);
459        let temp_buffer_size: usize = buffer_size;
460        let mut temp_buffer: Vec<u8> = vec![0; temp_buffer_size];
461        let mut full_frame: Vec<u8> = Vec::with_capacity(config.max_ws_frame_size);
462        let mut frame_count: usize = 0;
463        let mut is_client_response: bool = false;
464        let ws_read_timeout_ms: u64 =
465            (config.ws_read_timeout_ms >> 1) + (config.ws_read_timeout_ms & 1);
466        loop {
467            let timeout_duration: Duration = Duration::from_millis(ws_read_timeout_ms);
468            let len: usize = match timeout(
469                timeout_duration,
470                stream.write().await.read(&mut temp_buffer),
471            )
472            .await
473            {
474                Ok(result) => match result {
475                    Ok(len) => len,
476                    Err(err) => {
477                        if err.kind() == ErrorKind::ConnectionReset
478                            || err.kind() == ErrorKind::ConnectionAborted
479                        {
480                            return Err(RequestError::ClientDisconnected(HttpStatus::BadRequest));
481                        }
482                        return Err(RequestError::Unknown(HttpStatus::InternalServerError));
483                    }
484                },
485                Err(_) => {
486                    if !is_client_response {
487                        return Err(RequestError::ReadTimeoutNotSet(HttpStatus::RequestTimeout));
488                    }
489                    is_client_response = false;
490                    stream.send_body(&PING_FRAME).await.map_err(|_| {
491                        RequestError::WriteTimeoutNotSet(HttpStatus::InternalServerError)
492                    })?;
493                    stream.flush().await;
494                    continue;
495                }
496            };
497            if len == 0 {
498                return Err(RequestError::IncompleteWebSocketFrame(
499                    HttpStatus::BadRequest,
500                ));
501            }
502            dynamic_buffer.extend_from_slice(&temp_buffer[..len]);
503            while let Some((frame, consumed)) = WebSocketFrame::decode_ws_frame(&dynamic_buffer) {
504                is_client_response = true;
505                dynamic_buffer.drain(0..consumed);
506                frame_count += 1;
507                if frame_count > config.max_ws_frames {
508                    return Err(RequestError::TooManyHeaders(
509                        HttpStatus::RequestHeaderFieldsTooLarge,
510                    ));
511                }
512                match frame.get_opcode() {
513                    WebSocketOpcode::Close => {
514                        return Err(RequestError::ClientClosedConnection(HttpStatus::BadRequest));
515                    }
516                    WebSocketOpcode::Ping | WebSocketOpcode::Pong => {
517                        continue;
518                    }
519                    WebSocketOpcode::Text | WebSocketOpcode::Binary => {
520                        let payload_data: &[u8] = frame.get_payload_data();
521                        if payload_data.len() > config.max_ws_frame_size {
522                            return Err(RequestError::WebSocketFrameTooLarge(
523                                HttpStatus::PayloadTooLarge,
524                            ));
525                        }
526                        if full_frame.len() + payload_data.len() > config.max_ws_frame_size {
527                            return Err(RequestError::WebSocketFrameTooLarge(
528                                HttpStatus::PayloadTooLarge,
529                            ));
530                        }
531                        full_frame.extend_from_slice(payload_data);
532                        if *frame.get_fin() {
533                            let mut request: Request = self.clone();
534                            request.body = full_frame;
535                            return Ok(request);
536                        }
537                    }
538                    _ => {
539                        return Err(RequestError::WebSocketOpcodeUnsupported(
540                            HttpStatus::NotImplemented,
541                        ));
542                    }
543                }
544            }
545        }
546    }
547
548    /// Parses a query string as_ref key-value pairs.
549    ///
550    /// Expects format "key1=value1&key2=value2". Empty values are allowed.
551    ///
552    /// # Arguments
553    ///
554    /// - `&str` - The query string to parse.
555    ///
556    /// # Returns
557    ///
558    /// - `HashMap<String, String>` - The parsed query parameters.
559    fn parse_querys<Q>(query: Q) -> RequestQuerys
560    where
561        Q: AsRef<str>,
562    {
563        let mut query_map: RequestQuerys = hash_map_xx_hash3_64();
564        for pair in query.as_ref().split(AND) {
565            if let Some((key, value)) = pair.split_once(EQUAL) {
566                if !key.is_empty() {
567                    query_map.insert(key.to_string(), value.to_string());
568                }
569            } else if !pair.is_empty() {
570                query_map.insert(pair.to_string(), String::new());
571            }
572        }
573        query_map
574    }
575
576    /// Tries to get a query parameter value by key.
577    ///
578    /// The key type must implement AsRef<str> conversion.
579    ///
580    /// # Arguments
581    ///
582    /// - `AsRef<str>` - The query parameter key (implements AsRef<str>).
583    ///
584    /// # Returns
585    ///
586    /// - `Option<RequestQuerysValue>` - The parameter value if exists.
587    #[inline(always)]
588    pub fn try_get_query<K>(&self, key: K) -> Option<RequestQuerysValue>
589    where
590        K: AsRef<str>,
591    {
592        self.querys.get(key.as_ref()).cloned()
593    }
594
595    /// Gets a query parameter value by key.
596    ///
597    /// The key type must implement AsRef<str> conversion.
598    ///
599    /// # Arguments
600    ///
601    /// - `AsRef<str>` - The query parameter key (implements AsRef<str>).
602    ///
603    /// # Returns
604    ///
605    /// - `RequestQuerysValue` - The parameter value if exists.
606    ///
607    /// # Panics
608    ///
609    /// This function will panic if the query parameter key is not found.
610    #[inline(always)]
611    pub fn get_query<K>(&self, key: K) -> RequestQuerysValue
612    where
613        K: AsRef<str>,
614    {
615        self.try_get_query(key).unwrap()
616    }
617
618    /// Tries to retrieve the value of a request header by its key.
619    ///
620    /// # Arguments
621    ///
622    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
623    ///
624    /// # Returns
625    ///
626    /// - `Option<RequestHeadersValue>` - The optional header values.
627    #[inline(always)]
628    pub fn try_get_header<K>(&self, key: K) -> Option<RequestHeadersValue>
629    where
630        K: AsRef<str>,
631    {
632        self.headers.get(key.as_ref()).cloned()
633    }
634
635    /// Retrieves the value of a request header by its key.
636    ///
637    /// # Arguments
638    ///
639    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
640    ///
641    /// # Returns
642    ///
643    /// - `RequestHeadersValue` - The optional header values.
644    ///
645    /// # Panics
646    ///
647    /// This function will panic if the header key is not found.
648    #[inline(always)]
649    pub fn get_header<K>(&self, key: K) -> RequestHeadersValue
650    where
651        K: AsRef<str>,
652    {
653        self.try_get_header(key).unwrap()
654    }
655
656    /// Tries to retrieve the first value of a request header by its key.
657    ///
658    /// # Arguments
659    ///
660    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
661    ///
662    /// # Returns
663    ///
664    /// - `Option<RequestHeadersValueItem>` - The first header value if exists.
665    #[inline(always)]
666    pub fn try_get_header_front<K>(&self, key: K) -> Option<RequestHeadersValueItem>
667    where
668        K: AsRef<str>,
669    {
670        self.headers
671            .get(key.as_ref())
672            .and_then(|values| values.front().cloned())
673    }
674
675    /// Retrieves the first value of a request header by its key.
676    ///
677    /// # Arguments
678    ///
679    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
680    ///
681    /// # Returns
682    ///
683    /// - `RequestHeadersValueItem` - The first header value if exists.
684    ///
685    /// # Panics
686    ///
687    /// This function will panic if the header key is not found.
688    #[inline(always)]
689    pub fn get_header_front<K>(&self, key: K) -> RequestHeadersValueItem
690    where
691        K: AsRef<str>,
692    {
693        self.try_get_header_front(key).unwrap()
694    }
695
696    /// Tries to retrieve the last value of a request header by its key.
697    ///
698    /// # Arguments
699    ///
700    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
701    ///
702    /// # Returns
703    ///
704    /// - `Option<RequestHeadersValueItem>` - The last header value if exists.
705    #[inline(always)]
706    pub fn try_get_header_back<K>(&self, key: K) -> Option<RequestHeadersValueItem>
707    where
708        K: AsRef<str>,
709    {
710        self.headers
711            .get(key.as_ref())
712            .and_then(|values| values.back().cloned())
713    }
714
715    /// Retrieves the last value of a request header by its key.
716    ///
717    /// # Arguments
718    ///
719    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
720    ///
721    /// # Returns
722    ///
723    /// - `RequestHeadersValueItem` - The last header value if exists.
724    ///
725    /// # Panics
726    ///
727    /// This function will panic if the header key is not found.
728    #[inline(always)]
729    pub fn get_header_back<K>(&self, key: K) -> RequestHeadersValueItem
730    where
731        K: AsRef<str>,
732    {
733        self.try_get_header_back(key).unwrap()
734    }
735
736    /// Tries to retrieve the number of values for a specific header.
737    ///
738    /// # Arguments
739    ///
740    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
741    ///
742    /// # Returns
743    ///
744    /// - `Option<usize>` - The count of values for the header if exists.
745    #[inline(always)]
746    pub fn try_get_header_length<K>(&self, key: K) -> Option<usize>
747    where
748        K: AsRef<str>,
749    {
750        self.headers.get(key.as_ref()).map(|values| values.len())
751    }
752
753    /// Retrieves the number of values for a specific header.
754    ///
755    /// # Arguments
756    ///
757    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
758    ///
759    /// # Returns
760    ///
761    /// - `usize` - The count of values for the header.
762    ///
763    /// # Panics
764    ///
765    /// This function will panic if the header key is not found.
766    #[inline(always)]
767    pub fn get_header_length<K>(&self, key: K) -> usize
768    where
769        K: AsRef<str>,
770    {
771        self.try_get_header_length(key).unwrap()
772    }
773
774    /// Retrieves the total number of header values across all headers.
775    ///
776    /// # Returns
777    ///
778    /// - `usize` - The total count of all header values.
779    #[inline(always)]
780    pub fn get_headers_values_length(&self) -> usize {
781        self.headers.values().map(|values| values.len()).sum()
782    }
783
784    /// Retrieves the number of unique headers.
785    ///
786    /// # Returns
787    ///
788    /// - `usize` - The count of unique header keys.
789    #[inline(always)]
790    pub fn get_headers_length(&self) -> usize {
791        self.headers.len()
792    }
793
794    /// Checks if a specific header exists.
795    ///
796    /// # Arguments
797    ///
798    /// - `AsRef<str>` - The header key to check (must implement AsRef<str>).
799    ///
800    /// # Returns
801    ///
802    /// - `bool` - Whether the header exists.
803    #[inline(always)]
804    pub fn has_header<K>(&self, key: K) -> bool
805    where
806        K: AsRef<str>,
807    {
808        self.headers.contains_key(key.as_ref())
809    }
810
811    /// Checks if a header contains a specific value.
812    ///
813    /// # Arguments
814    ///
815    /// - `AsRef<str>` - The header key to check (must implement AsRef<str>).
816    /// - `AsRef<str>` - The value to search for (must implement AsRef<str>).
817    ///
818    /// # Returns
819    ///
820    /// - `bool` - Whether the header contains the value.
821    #[inline(always)]
822    pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
823    where
824        K: AsRef<str>,
825        V: AsRef<str>,
826    {
827        if let Some(values) = self.headers.get(key.as_ref()) {
828            values.contains(&value.as_ref().to_owned())
829        } else {
830            false
831        }
832    }
833
834    /// Retrieves the body content of the request as a UTF-8 encoded string.
835    ///
836    /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` as_ref a string.
837    /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character ().
838    ///
839    /// # Returns
840    ///
841    /// - `String` - The body content as a string.
842    #[inline(always)]
843    pub fn get_body_string(&self) -> String {
844        String::from_utf8_lossy(self.get_body()).into_owned()
845    }
846
847    /// Deserializes the body content of the request as_ref a specified type `T`.
848    ///
849    /// This method first retrieves the body content as a byte slice using `self.get_body()`.
850    /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
851    ///
852    /// # Arguments
853    ///
854    /// - `DeserializeOwned` - The target type to deserialize as_ref (must implement DeserializeOwned).
855    ///
856    /// # Returns
857    ///
858    /// - `Result<T, serde_json::Error>` - The deserialization result.
859    pub fn try_get_body_json<T>(&self) -> Result<T, serde_json::Error>
860    where
861        T: DeserializeOwned,
862    {
863        serde_json::from_slice(self.get_body())
864    }
865
866    /// Deserializes the body content of the request as_ref a specified type `T`.
867    ///
868    /// This method first retrieves the body content as a byte slice using `self.get_body()`.
869    /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
870    ///
871    /// # Arguments
872    ///
873    /// - `DeserializeOwned` - The target type to deserialize as_ref (must implement DeserializeOwned).
874    ///
875    /// # Returns
876    ///
877    /// - `T` - The deserialized body content.
878    ///
879    /// # Panics
880    ///
881    /// This function will panic if the deserialization fails.
882    pub fn get_body_json<T>(&self) -> T
883    where
884        T: DeserializeOwned,
885    {
886        self.try_get_body_json().unwrap()
887    }
888
889    /// Converts the request to a formatted string representation.
890    ///
891    /// This method provides a human-readable summary of the request, including its method,
892    /// host, version, path, query parameters, headers, and body information.
893    ///
894    /// # Returns
895    ///
896    /// - `String` - The formatted request details.
897    #[inline(always)]
898    pub fn get_string(&self) -> String {
899        let body: &Vec<u8> = self.get_body();
900        let body_type: &'static str = if std::str::from_utf8(body).is_ok() {
901            PLAIN
902        } else {
903            BINARY
904        };
905        format!(
906            "[Request] => [method]: {}; [host]: {}; [version]: {}; [path]: {}; [querys]: {:?}; [headers]: {:?}; [body]: {} bytes {};",
907            self.get_method(),
908            self.get_host(),
909            self.get_version(),
910            self.get_path(),
911            self.get_querys(),
912            self.get_headers(),
913            body.len(),
914            body_type
915        )
916    }
917
918    /// Retrieves the upgrade type from the request headers.
919    ///
920    /// This method looks for the `UPGRADE` header and attempts to parse its value
921    /// as_ref an `UpgradeType`. If the header is missing or the value is invalid,
922    /// it returns the default `UpgradeType`.
923    ///
924    /// # Returns
925    ///
926    /// - `UpgradeType` - The parsed upgrade type.
927    #[inline(always)]
928    pub fn get_upgrade_type(&self) -> UpgradeType {
929        let upgrade_type: UpgradeType = self
930            .try_get_header_back(UPGRADE)
931            .and_then(|data| data.parse::<UpgradeType>().ok())
932            .unwrap_or_default();
933        upgrade_type
934    }
935
936    /// Checks whether the WebSocket upgrade is enabled for this request.
937    ///
938    /// This method determines if the `UPGRADE` header indicates a WebSocket connection.
939    ///
940    /// # Returns
941    ///
942    /// - `bool` - Whether WebSocket upgrade is enabled.
943    #[inline(always)]
944    pub fn is_ws(&self) -> bool {
945        self.get_upgrade_type().is_ws()
946    }
947
948    /// Checks if the current upgrade type is HTTP/2 cleartext (h2c).
949    ///
950    /// # Returns
951    ///
952    /// - `bool` - Whether the upgrade type is h2c.
953    #[inline(always)]
954    pub fn is_h2c(&self) -> bool {
955        self.get_upgrade_type().is_h2c()
956    }
957
958    /// Checks if the current upgrade type is TLS (any version).
959    ///
960    /// # Returns
961    ///
962    /// - `bool` - Whether the upgrade type is TLS.
963    #[inline(always)]
964    pub fn is_tls(&self) -> bool {
965        self.get_upgrade_type().is_tls()
966    }
967
968    /// Checks whether the upgrade type is unknown.
969    ///
970    /// # Returns
971    ///
972    /// - `bool` - Whether the upgrade type is unknown.
973    #[inline(always)]
974    pub fn is_unknown_upgrade(&self) -> bool {
975        self.get_upgrade_type().is_unknown()
976    }
977
978    /// Checks if the HTTP version is HTTP/1.1 or higher.
979    ///
980    /// # Returns
981    ///
982    /// - `bool` - Whether the version is HTTP/1.1 or higher.
983    #[inline(always)]
984    pub fn is_http1_1_or_higher(&self) -> bool {
985        self.get_version().is_http1_1_or_higher()
986    }
987
988    /// Checks whether the HTTP version is HTTP/0.9.
989    ///
990    /// # Returns
991    ///
992    /// - `bool` - Whether the version is HTTP/0.9.
993    #[inline(always)]
994    pub fn is_http0_9(&self) -> bool {
995        self.get_version().is_http0_9()
996    }
997
998    /// Checks whether the HTTP version is HTTP/1.0.
999    ///
1000    /// # Returns
1001    ///
1002    /// - `bool` - Whether the version is HTTP/1.0.
1003    #[inline(always)]
1004    pub fn is_http1_0(&self) -> bool {
1005        self.get_version().is_http1_0()
1006    }
1007
1008    /// Checks whether the HTTP version is HTTP/1.1.
1009    ///
1010    /// # Returns
1011    ///
1012    /// - `bool` - Whether the version is HTTP/1.1.
1013    #[inline(always)]
1014    pub fn is_http1_1(&self) -> bool {
1015        self.get_version().is_http1_1()
1016    }
1017
1018    /// Checks whether the HTTP version is HTTP/2.
1019    ///
1020    /// # Returns
1021    ///
1022    /// - `bool` - Whether the version is HTTP/2.
1023    #[inline(always)]
1024    pub fn is_http2(&self) -> bool {
1025        self.get_version().is_http2()
1026    }
1027
1028    /// Checks whether the HTTP version is HTTP/3.
1029    ///
1030    /// # Returns
1031    ///
1032    /// - `bool` - Whether the version is HTTP/3.
1033    #[inline(always)]
1034    pub fn is_http3(&self) -> bool {
1035        self.get_version().is_http3()
1036    }
1037
1038    /// Checks whether the HTTP version is unknown.
1039    ///
1040    /// # Returns
1041    ///
1042    /// - `bool` - Whether the version is unknown.
1043    #[inline(always)]
1044    pub fn is_unknown_version(&self) -> bool {
1045        self.get_version().is_unknown()
1046    }
1047
1048    /// Checks whether the version belongs to the HTTP family.
1049    ///
1050    /// # Returns
1051    ///
1052    /// - `bool` - Whether the version is HTTP.
1053    #[inline(always)]
1054    pub fn is_http(&self) -> bool {
1055        self.get_version().is_http()
1056    }
1057
1058    /// Checks whether the request method is GET.
1059    ///
1060    /// # Returns
1061    ///
1062    /// - `bool` - Whether the method is GET.
1063    #[inline(always)]
1064    pub fn is_get(&self) -> bool {
1065        self.get_method().is_get()
1066    }
1067
1068    /// Checks whether the request method is POST.
1069    ///
1070    /// # Returns
1071    ///
1072    /// - `bool` - Whether the method is POST.
1073    #[inline(always)]
1074    pub fn is_post(&self) -> bool {
1075        self.get_method().is_post()
1076    }
1077
1078    /// Checks whether the request method is PUT.
1079    ///
1080    /// # Returns
1081    ///
1082    /// - `bool` - Whether the method is PUT.
1083    #[inline(always)]
1084    pub fn is_put(&self) -> bool {
1085        self.get_method().is_put()
1086    }
1087
1088    /// Checks whether the request method is DELETE.
1089    ///
1090    /// # Returns
1091    ///
1092    /// - `bool` - Whether the method is DELETE.
1093    #[inline(always)]
1094    pub fn is_delete(&self) -> bool {
1095        self.get_method().is_delete()
1096    }
1097
1098    /// Checks whether the request method is PATCH.
1099    ///
1100    /// # Returns
1101    ///
1102    /// - `bool` - Whether the method is PATCH.
1103    #[inline(always)]
1104    pub fn is_patch(&self) -> bool {
1105        self.get_method().is_patch()
1106    }
1107
1108    /// Checks whether the request method is HEAD.
1109    ///
1110    /// # Returns
1111    ///
1112    /// - `bool` - Whether the method is HEAD.
1113    #[inline(always)]
1114    pub fn is_head(&self) -> bool {
1115        self.get_method().is_head()
1116    }
1117
1118    /// Checks whether the request method is OPTIONS.
1119    ///
1120    /// # Returns
1121    ///
1122    /// - `bool` - Whether the method is OPTIONS.
1123    #[inline(always)]
1124    pub fn is_options(&self) -> bool {
1125        self.get_method().is_options()
1126    }
1127
1128    /// Checks whether the request method is CONNECT.
1129    ///
1130    /// # Returns
1131    ///
1132    /// - `bool` - Whether the method is CONNECT.
1133    #[inline(always)]
1134    pub fn is_connect(&self) -> bool {
1135        self.get_method().is_connect()
1136    }
1137
1138    /// Checks whether the request method is TRACE.
1139    ///
1140    /// # Returns
1141    ///
1142    /// - `bool` - Whether the method is TRACE.
1143    #[inline(always)]
1144    pub fn is_trace(&self) -> bool {
1145        self.get_method().is_trace()
1146    }
1147
1148    /// Checks whether the request method is UNKNOWN.
1149    ///
1150    /// # Returns
1151    ///
1152    /// - `bool` - Whether the method is UNKNOWN.
1153    #[inline(always)]
1154    pub fn is_unknown_method(&self) -> bool {
1155        self.get_method().is_unknown()
1156    }
1157
1158    /// Determines if a keep-alive connection should be enabled for this request.
1159    ///
1160    /// This function checks the `Connection` header and the HTTP version to determine
1161    /// if keep-alive should be enabled. The logic is as follows:
1162    ///
1163    /// 1. If the `Connection` header exists:
1164    ///    - Returns `true` if the header value is "keep-alive" (case-insensitive).
1165    ///    - Returns `false` if the header value is "close" (case-insensitive).
1166    /// 2. If no `Connection` header is present:
1167    ///    - Returns `true` if the HTTP version is 1.1 or higher.
1168    ///    - Returns `false` otherwise.
1169    ///
1170    /// # Returns
1171    ///
1172    /// - `bool` - Whether keep-alive should be enabled.
1173    #[inline(always)]
1174    pub fn is_enable_keep_alive(&self) -> bool {
1175        if let Some(connection_value) = self.try_get_header_back(CONNECTION) {
1176            if connection_value.eq_ignore_ascii_case(KEEP_ALIVE) {
1177                return true;
1178            } else if connection_value.eq_ignore_ascii_case(CLOSE) {
1179                return self.is_ws();
1180            }
1181        }
1182        self.is_http1_1_or_higher() || self.is_ws()
1183    }
1184
1185    /// Determines if keep-alive should be disabled for this request.
1186    ///
1187    /// # Returns
1188    ///
1189    /// - `bool` - Whether keep-alive should be disabled.
1190    #[inline(always)]
1191    pub fn is_disable_keep_alive(&self) -> bool {
1192        !self.is_enable_keep_alive()
1193    }
1194}