http_type/request/
impl.rs

1use crate::*;
2
3/// Provides a default value for `Request`.
4///
5/// Returns a new `Request` instance with all fields initialized to their default values.
6impl Default for Request {
7    #[inline(always)]
8    fn default() -> Self {
9        Self {
10            method: Method::default(),
11            host: String::new(),
12            version: HttpVersion::default(),
13            path: String::new(),
14            querys: hash_map_xx_hash3_64(),
15            headers: hash_map_xx_hash3_64(),
16            body: Vec::new(),
17        }
18    }
19}
20
21impl Request {
22    /// Creates a new instance of `Request`.
23    ///
24    /// # Returns
25    ///
26    /// - `Request` - A new request instance with default values.
27    #[inline(always)]
28    pub fn new() -> Self {
29        Self::default()
30    }
31
32    /// Parses an HTTP request from a buffered TCP stream reader.
33    ///
34    /// Reads request line, headers and body from the stream and constructs a Request object.
35    ///
36    /// # Arguments
37    ///
38    /// - `&mut BufReader<&mut TcpStream>` - The buffered TCP stream reader.
39    /// - `usize` - The buffer size for reading.
40    ///
41    /// # Returns
42    ///
43    /// - `Result<Request, RequestError>` - The parsed request or an error.
44    pub async fn http_from_reader(
45        reader: &mut BufReader<&mut TcpStream>,
46        buffer: usize,
47    ) -> RequestReaderHandleResult {
48        let mut request_line: String = String::with_capacity(buffer.min(DEFAULT_BUFFER_SIZE));
49        let _ = AsyncBufReadExt::read_line(reader, &mut request_line).await;
50        let parts: Vec<&str> = request_line.split_whitespace().collect();
51        let parts_len: usize = parts.len();
52        if parts_len < 3 {
53            return Err(RequestError::InvalidHttpRequestPartsLength(parts_len));
54        }
55        let method: RequestMethod = parts[0]
56            .parse::<RequestMethod>()
57            .unwrap_or(Method::UNKNOWN(parts[0].to_string()));
58        let full_path: RequestPath = parts[1].to_string();
59        let version: RequestVersion = parts[2]
60            .parse::<RequestVersion>()
61            .unwrap_or(RequestVersion::Unknown(parts[2].to_string()));
62        let hash_index: OptionUsize = full_path.find(HASH);
63        let query_index: OptionUsize = full_path.find(QUERY);
64        let query_string: String = query_index.map_or_else(String::new, |i| {
65            let temp: &str = &full_path[i + 1..];
66            if hash_index.is_none() || hash_index.unwrap() <= i {
67                return temp.to_owned();
68            }
69            temp.split(HASH).next().unwrap_or_default().to_owned()
70        });
71        let querys: RequestQuerys = Self::parse_querys(&query_string);
72        let path: RequestPath = if let Some(i) = query_index.or(hash_index) {
73            full_path[..i].to_owned()
74        } else {
75            full_path.to_owned()
76        };
77        let mut headers: RequestHeaders = hash_map_xx_hash3_64();
78        let mut host: RequestHost = String::new();
79        let mut content_length: usize = 0;
80        loop {
81            let mut header_line: String = String::with_capacity(buffer.min(DEFAULT_BUFFER_SIZE));
82            let _ = AsyncBufReadExt::read_line(reader, &mut header_line).await;
83            let header_line: &str = header_line.trim();
84            if header_line.is_empty() {
85                break;
86            }
87            if let Some((key_part, value_part)) = header_line.split_once(COLON) {
88                let key: String = key_part.trim().to_ascii_lowercase();
89                if key.is_empty() {
90                    continue;
91                }
92                let value: String = value_part.trim().to_string();
93                if key == HOST {
94                    host = value.clone();
95                } else if key == CONTENT_LENGTH {
96                    content_length = value.parse().unwrap_or(0);
97                }
98                headers.entry(key).or_default().push_back(value);
99            }
100        }
101        let mut body: RequestBody = vec![0; content_length];
102        if content_length > 0 {
103            let _ = AsyncReadExt::read_exact(reader, &mut body).await;
104        }
105        Ok(Request {
106            method,
107            host,
108            version,
109            path,
110            querys,
111            headers,
112            body,
113        })
114    }
115
116    /// Parses an HTTP request from a TCP stream.
117    ///
118    /// Wraps the stream in a buffered reader and delegates to `http_from_reader`.
119    ///
120    /// # Arguments
121    ///
122    /// - `&ArcRwLock<TcpStream>` - The TCP stream to read from.
123    /// - `usize` - The buffer size for reading.
124    ///
125    /// # Returns
126    ///
127    /// - `Result<Request, RequestError>` - The parsed request or an error.
128    pub async fn http_from_stream(
129        stream: &ArcRwLockStream,
130        buffer: usize,
131    ) -> RequestReaderHandleResult {
132        let mut buf_stream: RwLockWriteGuard<'_, TcpStream> = stream.write().await;
133        let mut reader: BufReader<&mut TcpStream> = BufReader::new(&mut buf_stream);
134        Self::http_from_reader(&mut reader, buffer).await
135    }
136
137    /// Parses a WebSocket request from a TCP stream.
138    ///
139    /// Wraps the stream in a buffered reader and delegates to `ws_from_reader`.
140    ///
141    /// # Arguments
142    ///
143    /// - `&ArcRwLock<TcpStream>` - The TCP stream to read from.
144    /// - `usize` - The buffer size for reading.
145    /// - `&mut Request` - The request template to populate.
146    ///
147    /// # Returns
148    ///
149    /// - `Result<Request, RequestError>` - The parsed WebSocket request or an error.
150    pub async fn ws_from_stream(
151        stream: &ArcRwLockStream,
152        buffer: usize,
153        request: &mut Self,
154    ) -> RequestReaderHandleResult {
155        let mut buf_stream: RwLockWriteGuard<'_, TcpStream> = stream.write().await;
156        let mut reader: BufReader<&mut TcpStream> = BufReader::new(&mut buf_stream);
157        Self::ws_from_reader(&mut reader, buffer, request).await
158    }
159
160    /// Parses a WebSocket request from a buffered TCP stream.
161    ///
162    /// Handles WebSocket frames including text, binary, ping, pong and close frames.
163    /// Assembles the request body from frame payload data.
164    ///
165    /// # Arguments
166    ///
167    /// - `&mut BufReader<&mut TcpStream>` - The buffered TCP stream reader.
168    /// - `usize` - The buffer size for reading frames.
169    /// - `&mut Request` - The request template to populate.
170    ///
171    /// # Returns
172    ///
173    /// - `Result<Request, RequestError>` - The parsed WebSocket request or an error.
174    pub async fn ws_from_reader(
175        reader: &mut BufReader<&mut TcpStream>,
176        buffer: usize,
177        request: &mut Self,
178    ) -> RequestReaderHandleResult {
179        let mut dynamic_buffer: Vec<u8> = Vec::with_capacity(buffer.min(DEFAULT_BUFFER_SIZE));
180        let temp_buffer_size: usize = buffer.min(DEFAULT_BUFFER_SIZE);
181        let mut temp_buffer: Vec<u8> = vec![0; temp_buffer_size];
182        let mut full_frame: Vec<u8> = Vec::with_capacity(buffer.min(MAX_FRAME_SIZE));
183        let mut error_handle = || {
184            request.body.clear();
185        };
186        loop {
187            let len: usize = match reader.read(&mut temp_buffer).await {
188                Ok(len) => len,
189                Err(err) => {
190                    error_handle();
191                    if err.kind() == ErrorKind::ConnectionReset
192                        || err.kind() == ErrorKind::ConnectionAborted
193                    {
194                        return Err(RequestError::ClientDisconnected);
195                    }
196                    return Err(RequestError::InvalidWebSocketRequest(err.to_string()));
197                }
198            };
199            if len == 0 {
200                error_handle();
201                return Err(RequestError::IncompleteWebSocketFrame);
202            }
203            dynamic_buffer.extend_from_slice(&temp_buffer[..len]);
204            while let Some((frame, consumed)) = WebSocketFrame::decode_ws_frame(&dynamic_buffer) {
205                dynamic_buffer.drain(0..consumed);
206                match frame.get_opcode() {
207                    WebSocketOpcode::Close => {
208                        error_handle();
209                        return Err(RequestError::ClientClosedConnection);
210                    }
211                    WebSocketOpcode::Ping | WebSocketOpcode::Pong => {
212                        continue;
213                    }
214                    WebSocketOpcode::Text | WebSocketOpcode::Binary => {
215                        full_frame.extend_from_slice(frame.get_payload_data());
216                        if *frame.get_fin() {
217                            let mut request: Request = request.clone();
218                            request.body = full_frame;
219                            return Ok(request);
220                        }
221                    }
222                    _ => {
223                        error_handle();
224                        return Err(RequestError::InvalidWebSocketFrame(
225                            "Unsupported opcode".to_owned(),
226                        ));
227                    }
228                }
229            }
230        }
231    }
232
233    /// Parses a query string as_ref key-value pairs.
234    ///
235    /// Expects format "key1=value1&key2=value2". Empty values are allowed.
236    ///
237    /// # Arguments
238    ///
239    /// - `&str` - The query string to parse.
240    ///
241    /// # Returns
242    ///
243    /// - `HashMap<String, String>` - The parsed query parameters.
244    fn parse_querys<Q>(query: Q) -> RequestQuerys
245    where
246        Q: AsRef<str>,
247    {
248        let mut query_map: RequestQuerys = hash_map_xx_hash3_64();
249        for pair in query.as_ref().split(AND) {
250            if let Some((key, value)) = pair.split_once(EQUAL) {
251                if !key.is_empty() {
252                    query_map.insert(key.to_string(), value.to_string());
253                }
254            } else if !pair.is_empty() {
255                query_map.insert(pair.to_string(), String::new());
256            }
257        }
258        query_map
259    }
260
261    /// Tries to get a query parameter value by key.
262    ///
263    /// The key type must implement AsRef<str> conversion.
264    ///
265    /// # Arguments
266    ///
267    /// - `AsRef<str>` - The query parameter key (implements AsRef<str>).
268    ///
269    /// # Returns
270    ///
271    /// - `OptionRequestQuerysValue` - The parameter value if exists.
272    #[inline(always)]
273    pub fn try_get_query<K>(&self, key: K) -> OptionRequestQuerysValue
274    where
275        K: AsRef<str>,
276    {
277        self.querys.get(key.as_ref()).cloned()
278    }
279
280    /// Gets a query parameter value by key.
281    ///
282    /// The key type must implement AsRef<str> conversion.
283    ///
284    /// # Arguments
285    ///
286    /// - `AsRef<str>` - The query parameter key (implements AsRef<str>).
287    ///
288    /// # Returns
289    ///
290    /// - `RequestQuerysValue` - The parameter value if exists.
291    #[inline(always)]
292    pub fn get_query<K>(&self, key: K) -> RequestQuerysValue
293    where
294        K: AsRef<str>,
295    {
296        self.try_get_query(key).unwrap()
297    }
298
299    /// Tries to retrieve the value of a request header by its key.
300    ///
301    /// # Arguments
302    ///
303    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
304    ///
305    /// # Returns
306    ///
307    /// - `OptionRequestHeadersValue` - The optional header values.
308    #[inline(always)]
309    pub fn try_get_header<K>(&self, key: K) -> OptionRequestHeadersValue
310    where
311        K: AsRef<str>,
312    {
313        self.headers.get(key.as_ref()).cloned()
314    }
315
316    /// Retrieves the value of a request header by its key.
317    ///
318    /// # Arguments
319    ///
320    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
321    ///
322    /// # Returns
323    ///
324    /// - `RequestHeadersValue` - The optional header values.
325    #[inline(always)]
326    pub fn get_header<K>(&self, key: K) -> RequestHeadersValue
327    where
328        K: AsRef<str>,
329    {
330        self.try_get_header(key).unwrap()
331    }
332
333    /// Tries to retrieve the first value of a request header by its key.
334    ///
335    /// # Arguments
336    ///
337    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
338    ///
339    /// # Returns
340    ///
341    /// - `OptionRequestHeadersValueItem` - The first header value if exists.
342    #[inline(always)]
343    pub fn try_get_header_front<K>(&self, key: K) -> OptionRequestHeadersValueItem
344    where
345        K: AsRef<str>,
346    {
347        self.headers
348            .get(key.as_ref())
349            .and_then(|values| values.front().cloned())
350    }
351
352    /// Retrieves the first value of a request header by its key.
353    ///
354    /// # Arguments
355    ///
356    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
357    ///
358    /// # Returns
359    ///
360    /// - `RequestHeadersValueItem` - The first header value if exists.
361    #[inline(always)]
362    pub fn get_header_front<K>(&self, key: K) -> RequestHeadersValueItem
363    where
364        K: AsRef<str>,
365    {
366        self.try_get_header_front(key).unwrap()
367    }
368
369    /// Tries to retrieve the last value of a request header by its key.
370    ///
371    /// # Arguments
372    ///
373    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
374    ///
375    /// # Returns
376    ///
377    /// - `OptionRequestHeadersValueItem` - The last header value if exists.
378    #[inline(always)]
379    pub fn try_get_header_back<K>(&self, key: K) -> OptionRequestHeadersValueItem
380    where
381        K: AsRef<str>,
382    {
383        self.headers
384            .get(key.as_ref())
385            .and_then(|values| values.back().cloned())
386    }
387
388    /// Retrieves the last value of a request header by its key.
389    ///
390    /// # Arguments
391    ///
392    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
393    ///
394    /// # Returns
395    ///
396    /// - `RequestHeadersValueItem` - The last header value if exists.
397    #[inline(always)]
398    pub fn get_header_back<K>(&self, key: K) -> RequestHeadersValueItem
399    where
400        K: AsRef<str>,
401    {
402        self.try_get_header_back(key).unwrap()
403    }
404
405    /// Retrieves the number of values for a specific header.
406    ///
407    /// # Arguments
408    ///
409    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
410    ///
411    /// # Returns
412    ///
413    /// - `usize` - The count of values for the header.
414    #[inline(always)]
415    pub fn get_header_length<K>(&self, key: K) -> usize
416    where
417        K: AsRef<str>,
418    {
419        self.headers
420            .get(key.as_ref())
421            .map(|values| values.len())
422            .unwrap_or(0)
423    }
424
425    /// Retrieves the total number of header values across all headers.
426    ///
427    /// # Returns
428    ///
429    /// - `usize` - The total count of all header values.
430    #[inline(always)]
431    pub fn get_headers_values_length(&self) -> usize {
432        self.headers.values().map(|values| values.len()).sum()
433    }
434
435    /// Retrieves the number of unique headers.
436    ///
437    /// # Returns
438    ///
439    /// - `usize` - The count of unique header keys.
440    #[inline(always)]
441    pub fn get_headers_length(&self) -> usize {
442        self.headers.len()
443    }
444
445    /// Checks if a specific header exists.
446    ///
447    /// # Arguments
448    ///
449    /// - `AsRef<str>` - The header key to check (must implement AsRef<str>).
450    ///
451    /// # Returns
452    ///
453    /// - `bool` - Whether the header exists.
454    #[inline(always)]
455    pub fn has_header<K>(&self, key: K) -> bool
456    where
457        K: AsRef<str>,
458    {
459        self.headers.contains_key(key.as_ref())
460    }
461
462    /// Checks if a header contains a specific value.
463    ///
464    /// # Arguments
465    ///
466    /// - `AsRef<str>` - The header key to check (must implement AsRef<str>).
467    /// - `AsRef<str>` - The value to search for (must implement AsRef<str>).
468    ///
469    /// # Returns
470    ///
471    /// - `bool` - Whether the header contains the value.
472    #[inline(always)]
473    pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
474    where
475        K: AsRef<str>,
476        V: AsRef<str>,
477    {
478        if let Some(values) = self.headers.get(key.as_ref()) {
479            values.contains(&value.as_ref().to_owned())
480        } else {
481            false
482        }
483    }
484
485    /// Retrieves the body content of the request as a UTF-8 encoded string.
486    ///
487    /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` as_ref a string.
488    /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character ().
489    ///
490    /// # Returns
491    ///
492    /// - `String` - The body content as a string.
493    #[inline(always)]
494    pub fn get_body_string(&self) -> String {
495        String::from_utf8_lossy(self.get_body()).into_owned()
496    }
497
498    /// Deserializes the body content of the request as_ref a specified type `T`.
499    ///
500    /// This method first retrieves the body content as a byte slice using `self.get_body()`.
501    /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
502    ///
503    /// # Arguments
504    ///
505    /// - `DeserializeOwned` - The target type to deserialize as_ref (must implement DeserializeOwned).
506    ///
507    /// # Returns
508    ///
509    /// - `ResultJsonError<T>` - The deserialization result.
510    pub fn get_body_json<T>(&self) -> ResultJsonError<T>
511    where
512        T: DeserializeOwned,
513    {
514        json_from_slice(self.get_body())
515    }
516
517    /// Converts the request to a formatted string representation.
518    ///
519    /// This method provides a human-readable summary of the request, including its method,
520    /// host, version, path, query parameters, headers, and body information.
521    ///
522    /// # Returns
523    ///
524    /// - `String` - The formatted request details.
525    #[inline(always)]
526    pub fn get_string(&self) -> String {
527        let body: &Vec<u8> = self.get_body();
528        let body_type: &'static str = if std::str::from_utf8(body).is_ok() {
529            PLAIN
530        } else {
531            BINARY
532        };
533        format!(
534            "[Request] => [method]: {}; [host]: {}; [version]: {}; [path]: {}; [querys]: {:?}; [headers]: {:?}; [body]: {} bytes {};",
535            self.get_method(),
536            self.get_host(),
537            self.get_version(),
538            self.get_path(),
539            self.get_querys(),
540            self.get_headers(),
541            body.len(),
542            body_type
543        )
544    }
545
546    /// Retrieves the upgrade type from the request headers.
547    ///
548    /// This method looks for the `UPGRADE` header and attempts to parse its value
549    /// as_ref an `UpgradeType`. If the header is missing or the value is invalid,
550    /// it returns the default `UpgradeType`.
551    ///
552    /// # Returns
553    ///
554    /// - `UpgradeType` - The parsed upgrade type.
555    #[inline(always)]
556    pub fn get_upgrade_type(&self) -> UpgradeType {
557        let upgrade_type: UpgradeType = self
558            .try_get_header_back(UPGRADE)
559            .and_then(|data| data.parse::<UpgradeType>().ok())
560            .unwrap_or_default();
561        upgrade_type
562    }
563
564    /// Checks whether the WebSocket upgrade is enabled for this request.
565    ///
566    /// This method determines if the `UPGRADE` header indicates a WebSocket connection.
567    ///
568    /// # Returns
569    ///
570    /// - `bool` - Whether WebSocket upgrade is enabled.
571    #[inline(always)]
572    pub fn is_ws(&self) -> bool {
573        self.get_upgrade_type().is_ws()
574    }
575
576    /// Checks if the current upgrade type is HTTP/2 cleartext (h2c).
577    ///
578    /// # Returns
579    ///
580    /// - `bool` - Whether the upgrade type is h2c.
581    #[inline(always)]
582    pub fn is_h2c(&self) -> bool {
583        self.get_upgrade_type().is_h2c()
584    }
585
586    /// Checks if the current upgrade type is TLS (any version).
587    ///
588    /// # Returns
589    ///
590    /// - `bool` - Whether the upgrade type is TLS.
591    #[inline(always)]
592    pub fn is_tls(&self) -> bool {
593        self.get_upgrade_type().is_tls()
594    }
595
596    /// Checks whether the upgrade type is unknown.
597    ///
598    /// # Returns
599    ///
600    /// - `bool` - Whether the upgrade type is unknown.
601    #[inline(always)]
602    pub fn is_unknown_upgrade(&self) -> bool {
603        self.get_upgrade_type().is_unknown()
604    }
605
606    /// Checks if the HTTP version is HTTP/1.1 or higher.
607    ///
608    /// # Returns
609    ///
610    /// - `bool` - Whether the version is HTTP/1.1 or higher.
611    #[inline(always)]
612    pub fn is_http1_1_or_higher(&self) -> bool {
613        self.get_version().is_http1_1_or_higher()
614    }
615
616    /// Checks whether the HTTP version is HTTP/0.9.
617    ///
618    /// # Returns
619    ///
620    /// - `bool` - Whether the version is HTTP/0.9.
621    #[inline(always)]
622    pub fn is_http0_9(&self) -> bool {
623        self.get_version().is_http0_9()
624    }
625
626    /// Checks whether the HTTP version is HTTP/1.0.
627    ///
628    /// # Returns
629    ///
630    /// - `bool` - Whether the version is HTTP/1.0.
631    #[inline(always)]
632    pub fn is_http1_0(&self) -> bool {
633        self.get_version().is_http1_0()
634    }
635
636    /// Checks whether the HTTP version is HTTP/1.1.
637    ///
638    /// # Returns
639    ///
640    /// - `bool` - Whether the version is HTTP/1.1.
641    #[inline(always)]
642    pub fn is_http1_1(&self) -> bool {
643        self.get_version().is_http1_1()
644    }
645
646    /// Checks whether the HTTP version is HTTP/2.
647    ///
648    /// # Returns
649    ///
650    /// - `bool` - Whether the version is HTTP/2.
651    #[inline(always)]
652    pub fn is_http2(&self) -> bool {
653        self.get_version().is_http2()
654    }
655
656    /// Checks whether the HTTP version is HTTP/3.
657    ///
658    /// # Returns
659    ///
660    /// - `bool` - Whether the version is HTTP/3.
661    #[inline(always)]
662    pub fn is_http3(&self) -> bool {
663        self.get_version().is_http3()
664    }
665
666    /// Checks whether the HTTP version is unknown.
667    ///
668    /// # Returns
669    ///
670    /// - `bool` - Whether the version is unknown.
671    #[inline(always)]
672    pub fn is_unknown_version(&self) -> bool {
673        self.get_version().is_unknown()
674    }
675
676    /// Checks whether the version belongs to the HTTP family.
677    ///
678    /// # Returns
679    ///
680    /// - `bool` - Whether the version is HTTP.
681    #[inline(always)]
682    pub fn is_http(&self) -> bool {
683        self.get_version().is_http()
684    }
685
686    /// Checks whether the request method is GET.
687    ///
688    /// # Returns
689    ///
690    /// - `bool` - Whether the method is GET.
691    #[inline(always)]
692    pub fn is_get(&self) -> bool {
693        self.get_method().is_get()
694    }
695
696    /// Checks whether the request method is POST.
697    ///
698    /// # Returns
699    ///
700    /// - `bool` - Whether the method is POST.
701    #[inline(always)]
702    pub fn is_post(&self) -> bool {
703        self.get_method().is_post()
704    }
705
706    /// Checks whether the request method is PUT.
707    ///
708    /// # Returns
709    ///
710    /// - `bool` - Whether the method is PUT.
711    #[inline(always)]
712    pub fn is_put(&self) -> bool {
713        self.get_method().is_put()
714    }
715
716    /// Checks whether the request method is DELETE.
717    ///
718    /// # Returns
719    ///
720    /// - `bool` - Whether the method is DELETE.
721    #[inline(always)]
722    pub fn is_delete(&self) -> bool {
723        self.get_method().is_delete()
724    }
725
726    /// Checks whether the request method is PATCH.
727    ///
728    /// # Returns
729    ///
730    /// - `bool` - Whether the method is PATCH.
731    #[inline(always)]
732    pub fn is_patch(&self) -> bool {
733        self.get_method().is_patch()
734    }
735
736    /// Checks whether the request method is HEAD.
737    ///
738    /// # Returns
739    ///
740    /// - `bool` - Whether the method is HEAD.
741    #[inline(always)]
742    pub fn is_head(&self) -> bool {
743        self.get_method().is_head()
744    }
745
746    /// Checks whether the request method is OPTIONS.
747    ///
748    /// # Returns
749    ///
750    /// - `bool` - Whether the method is OPTIONS.
751    #[inline(always)]
752    pub fn is_options(&self) -> bool {
753        self.get_method().is_options()
754    }
755
756    /// Checks whether the request method is CONNECT.
757    ///
758    /// # Returns
759    ///
760    /// - `bool` - Whether the method is CONNECT.
761    #[inline(always)]
762    pub fn is_connect(&self) -> bool {
763        self.get_method().is_connect()
764    }
765
766    /// Checks whether the request method is TRACE.
767    ///
768    /// # Returns
769    ///
770    /// - `bool` - Whether the method is TRACE.
771    #[inline(always)]
772    pub fn is_trace(&self) -> bool {
773        self.get_method().is_trace()
774    }
775
776    /// Checks whether the request method is UNKNOWN.
777    ///
778    /// # Returns
779    ///
780    /// - `bool` - Whether the method is UNKNOWN.
781    #[inline(always)]
782    pub fn is_unknown_method(&self) -> bool {
783        self.get_method().is_unknown()
784    }
785
786    /// Determines if a keep-alive connection should be enabled for this request.
787    ///
788    /// This function checks the `Connection` header and the HTTP version to determine
789    /// if keep-alive should be enabled. The logic is as follows:
790    ///
791    /// 1. If the `Connection` header exists:
792    ///    - Returns `true` if the header value is "keep-alive" (case-insensitive).
793    ///    - Returns `false` if the header value is "close" (case-insensitive).
794    /// 2. If no `Connection` header is present:
795    ///    - Returns `true` if the HTTP version is 1.1 or higher.
796    ///    - Returns `false` otherwise.
797    ///
798    /// # Returns
799    ///
800    /// - `bool` - Whether keep-alive should be enabled.
801    #[inline(always)]
802    pub fn is_enable_keep_alive(&self) -> bool {
803        if let Some(connection_value) = self.try_get_header_back(CONNECTION) {
804            if connection_value.eq_ignore_ascii_case(KEEP_ALIVE) {
805                return true;
806            } else if connection_value.eq_ignore_ascii_case(CLOSE) {
807                return self.is_ws();
808            }
809        }
810        self.is_http1_1_or_higher() || self.is_ws()
811    }
812
813    /// Determines if keep-alive should be disabled for this request.
814    ///
815    /// # Returns
816    ///
817    /// - `bool` - Whether keep-alive should be disabled.
818    #[inline(always)]
819    pub fn is_disable_keep_alive(&self) -> bool {
820        !self.is_enable_keep_alive()
821    }
822}