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 /// Tries to retrieve 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 /// - `Option<usize>` - The count of values for the header if exists.
414 #[inline(always)]
415 pub fn try_get_header_length<K>(&self, key: K) -> Option<usize>
416 where
417 K: AsRef<str>,
418 {
419 self.headers.get(key.as_ref()).map(|values| values.len())
420 }
421
422 /// Retrieves the number of values for a specific header.
423 ///
424 /// # Arguments
425 ///
426 /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
427 ///
428 /// # Returns
429 ///
430 /// - `usize` - The count of values for the header.
431 #[inline(always)]
432 pub fn get_header_length<K>(&self, key: K) -> usize
433 where
434 K: AsRef<str>,
435 {
436 self.try_get_header_length(key).unwrap()
437 }
438
439 /// Retrieves the total number of header values across all headers.
440 ///
441 /// # Returns
442 ///
443 /// - `usize` - The total count of all header values.
444 #[inline(always)]
445 pub fn get_headers_values_length(&self) -> usize {
446 self.headers.values().map(|values| values.len()).sum()
447 }
448
449 /// Retrieves the number of unique headers.
450 ///
451 /// # Returns
452 ///
453 /// - `usize` - The count of unique header keys.
454 #[inline(always)]
455 pub fn get_headers_length(&self) -> usize {
456 self.headers.len()
457 }
458
459 /// Checks if a specific header exists.
460 ///
461 /// # Arguments
462 ///
463 /// - `AsRef<str>` - The header key to check (must implement AsRef<str>).
464 ///
465 /// # Returns
466 ///
467 /// - `bool` - Whether the header exists.
468 #[inline(always)]
469 pub fn has_header<K>(&self, key: K) -> bool
470 where
471 K: AsRef<str>,
472 {
473 self.headers.contains_key(key.as_ref())
474 }
475
476 /// Checks if a header contains a specific value.
477 ///
478 /// # Arguments
479 ///
480 /// - `AsRef<str>` - The header key to check (must implement AsRef<str>).
481 /// - `AsRef<str>` - The value to search for (must implement AsRef<str>).
482 ///
483 /// # Returns
484 ///
485 /// - `bool` - Whether the header contains the value.
486 #[inline(always)]
487 pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
488 where
489 K: AsRef<str>,
490 V: AsRef<str>,
491 {
492 if let Some(values) = self.headers.get(key.as_ref()) {
493 values.contains(&value.as_ref().to_owned())
494 } else {
495 false
496 }
497 }
498
499 /// Retrieves the body content of the request as a UTF-8 encoded string.
500 ///
501 /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` as_ref a string.
502 /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character ().
503 ///
504 /// # Returns
505 ///
506 /// - `String` - The body content as a string.
507 #[inline(always)]
508 pub fn get_body_string(&self) -> String {
509 String::from_utf8_lossy(self.get_body()).into_owned()
510 }
511
512 /// Deserializes the body content of the request as_ref a specified type `T`.
513 ///
514 /// This method first retrieves the body content as a byte slice using `self.get_body()`.
515 /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
516 ///
517 /// # Arguments
518 ///
519 /// - `DeserializeOwned` - The target type to deserialize as_ref (must implement DeserializeOwned).
520 ///
521 /// # Returns
522 ///
523 /// - `ResultJsonError<T>` - The deserialization result.
524 pub fn get_body_json<T>(&self) -> ResultJsonError<T>
525 where
526 T: DeserializeOwned,
527 {
528 json_from_slice(self.get_body())
529 }
530
531 /// Converts the request to a formatted string representation.
532 ///
533 /// This method provides a human-readable summary of the request, including its method,
534 /// host, version, path, query parameters, headers, and body information.
535 ///
536 /// # Returns
537 ///
538 /// - `String` - The formatted request details.
539 #[inline(always)]
540 pub fn get_string(&self) -> String {
541 let body: &Vec<u8> = self.get_body();
542 let body_type: &'static str = if std::str::from_utf8(body).is_ok() {
543 PLAIN
544 } else {
545 BINARY
546 };
547 format!(
548 "[Request] => [method]: {}; [host]: {}; [version]: {}; [path]: {}; [querys]: {:?}; [headers]: {:?}; [body]: {} bytes {};",
549 self.get_method(),
550 self.get_host(),
551 self.get_version(),
552 self.get_path(),
553 self.get_querys(),
554 self.get_headers(),
555 body.len(),
556 body_type
557 )
558 }
559
560 /// Retrieves the upgrade type from the request headers.
561 ///
562 /// This method looks for the `UPGRADE` header and attempts to parse its value
563 /// as_ref an `UpgradeType`. If the header is missing or the value is invalid,
564 /// it returns the default `UpgradeType`.
565 ///
566 /// # Returns
567 ///
568 /// - `UpgradeType` - The parsed upgrade type.
569 #[inline(always)]
570 pub fn get_upgrade_type(&self) -> UpgradeType {
571 let upgrade_type: UpgradeType = self
572 .try_get_header_back(UPGRADE)
573 .and_then(|data| data.parse::<UpgradeType>().ok())
574 .unwrap_or_default();
575 upgrade_type
576 }
577
578 /// Checks whether the WebSocket upgrade is enabled for this request.
579 ///
580 /// This method determines if the `UPGRADE` header indicates a WebSocket connection.
581 ///
582 /// # Returns
583 ///
584 /// - `bool` - Whether WebSocket upgrade is enabled.
585 #[inline(always)]
586 pub fn is_ws(&self) -> bool {
587 self.get_upgrade_type().is_ws()
588 }
589
590 /// Checks if the current upgrade type is HTTP/2 cleartext (h2c).
591 ///
592 /// # Returns
593 ///
594 /// - `bool` - Whether the upgrade type is h2c.
595 #[inline(always)]
596 pub fn is_h2c(&self) -> bool {
597 self.get_upgrade_type().is_h2c()
598 }
599
600 /// Checks if the current upgrade type is TLS (any version).
601 ///
602 /// # Returns
603 ///
604 /// - `bool` - Whether the upgrade type is TLS.
605 #[inline(always)]
606 pub fn is_tls(&self) -> bool {
607 self.get_upgrade_type().is_tls()
608 }
609
610 /// Checks whether the upgrade type is unknown.
611 ///
612 /// # Returns
613 ///
614 /// - `bool` - Whether the upgrade type is unknown.
615 #[inline(always)]
616 pub fn is_unknown_upgrade(&self) -> bool {
617 self.get_upgrade_type().is_unknown()
618 }
619
620 /// Checks if the HTTP version is HTTP/1.1 or higher.
621 ///
622 /// # Returns
623 ///
624 /// - `bool` - Whether the version is HTTP/1.1 or higher.
625 #[inline(always)]
626 pub fn is_http1_1_or_higher(&self) -> bool {
627 self.get_version().is_http1_1_or_higher()
628 }
629
630 /// Checks whether the HTTP version is HTTP/0.9.
631 ///
632 /// # Returns
633 ///
634 /// - `bool` - Whether the version is HTTP/0.9.
635 #[inline(always)]
636 pub fn is_http0_9(&self) -> bool {
637 self.get_version().is_http0_9()
638 }
639
640 /// Checks whether the HTTP version is HTTP/1.0.
641 ///
642 /// # Returns
643 ///
644 /// - `bool` - Whether the version is HTTP/1.0.
645 #[inline(always)]
646 pub fn is_http1_0(&self) -> bool {
647 self.get_version().is_http1_0()
648 }
649
650 /// Checks whether the HTTP version is HTTP/1.1.
651 ///
652 /// # Returns
653 ///
654 /// - `bool` - Whether the version is HTTP/1.1.
655 #[inline(always)]
656 pub fn is_http1_1(&self) -> bool {
657 self.get_version().is_http1_1()
658 }
659
660 /// Checks whether the HTTP version is HTTP/2.
661 ///
662 /// # Returns
663 ///
664 /// - `bool` - Whether the version is HTTP/2.
665 #[inline(always)]
666 pub fn is_http2(&self) -> bool {
667 self.get_version().is_http2()
668 }
669
670 /// Checks whether the HTTP version is HTTP/3.
671 ///
672 /// # Returns
673 ///
674 /// - `bool` - Whether the version is HTTP/3.
675 #[inline(always)]
676 pub fn is_http3(&self) -> bool {
677 self.get_version().is_http3()
678 }
679
680 /// Checks whether the HTTP version is unknown.
681 ///
682 /// # Returns
683 ///
684 /// - `bool` - Whether the version is unknown.
685 #[inline(always)]
686 pub fn is_unknown_version(&self) -> bool {
687 self.get_version().is_unknown()
688 }
689
690 /// Checks whether the version belongs to the HTTP family.
691 ///
692 /// # Returns
693 ///
694 /// - `bool` - Whether the version is HTTP.
695 #[inline(always)]
696 pub fn is_http(&self) -> bool {
697 self.get_version().is_http()
698 }
699
700 /// Checks whether the request method is GET.
701 ///
702 /// # Returns
703 ///
704 /// - `bool` - Whether the method is GET.
705 #[inline(always)]
706 pub fn is_get(&self) -> bool {
707 self.get_method().is_get()
708 }
709
710 /// Checks whether the request method is POST.
711 ///
712 /// # Returns
713 ///
714 /// - `bool` - Whether the method is POST.
715 #[inline(always)]
716 pub fn is_post(&self) -> bool {
717 self.get_method().is_post()
718 }
719
720 /// Checks whether the request method is PUT.
721 ///
722 /// # Returns
723 ///
724 /// - `bool` - Whether the method is PUT.
725 #[inline(always)]
726 pub fn is_put(&self) -> bool {
727 self.get_method().is_put()
728 }
729
730 /// Checks whether the request method is DELETE.
731 ///
732 /// # Returns
733 ///
734 /// - `bool` - Whether the method is DELETE.
735 #[inline(always)]
736 pub fn is_delete(&self) -> bool {
737 self.get_method().is_delete()
738 }
739
740 /// Checks whether the request method is PATCH.
741 ///
742 /// # Returns
743 ///
744 /// - `bool` - Whether the method is PATCH.
745 #[inline(always)]
746 pub fn is_patch(&self) -> bool {
747 self.get_method().is_patch()
748 }
749
750 /// Checks whether the request method is HEAD.
751 ///
752 /// # Returns
753 ///
754 /// - `bool` - Whether the method is HEAD.
755 #[inline(always)]
756 pub fn is_head(&self) -> bool {
757 self.get_method().is_head()
758 }
759
760 /// Checks whether the request method is OPTIONS.
761 ///
762 /// # Returns
763 ///
764 /// - `bool` - Whether the method is OPTIONS.
765 #[inline(always)]
766 pub fn is_options(&self) -> bool {
767 self.get_method().is_options()
768 }
769
770 /// Checks whether the request method is CONNECT.
771 ///
772 /// # Returns
773 ///
774 /// - `bool` - Whether the method is CONNECT.
775 #[inline(always)]
776 pub fn is_connect(&self) -> bool {
777 self.get_method().is_connect()
778 }
779
780 /// Checks whether the request method is TRACE.
781 ///
782 /// # Returns
783 ///
784 /// - `bool` - Whether the method is TRACE.
785 #[inline(always)]
786 pub fn is_trace(&self) -> bool {
787 self.get_method().is_trace()
788 }
789
790 /// Checks whether the request method is UNKNOWN.
791 ///
792 /// # Returns
793 ///
794 /// - `bool` - Whether the method is UNKNOWN.
795 #[inline(always)]
796 pub fn is_unknown_method(&self) -> bool {
797 self.get_method().is_unknown()
798 }
799
800 /// Determines if a keep-alive connection should be enabled for this request.
801 ///
802 /// This function checks the `Connection` header and the HTTP version to determine
803 /// if keep-alive should be enabled. The logic is as follows:
804 ///
805 /// 1. If the `Connection` header exists:
806 /// - Returns `true` if the header value is "keep-alive" (case-insensitive).
807 /// - Returns `false` if the header value is "close" (case-insensitive).
808 /// 2. If no `Connection` header is present:
809 /// - Returns `true` if the HTTP version is 1.1 or higher.
810 /// - Returns `false` otherwise.
811 ///
812 /// # Returns
813 ///
814 /// - `bool` - Whether keep-alive should be enabled.
815 #[inline(always)]
816 pub fn is_enable_keep_alive(&self) -> bool {
817 if let Some(connection_value) = self.try_get_header_back(CONNECTION) {
818 if connection_value.eq_ignore_ascii_case(KEEP_ALIVE) {
819 return true;
820 } else if connection_value.eq_ignore_ascii_case(CLOSE) {
821 return self.is_ws();
822 }
823 }
824 self.is_http1_1_or_higher() || self.is_ws()
825 }
826
827 /// Determines if keep-alive should be disabled for this request.
828 ///
829 /// # Returns
830 ///
831 /// - `bool` - Whether keep-alive should be disabled.
832 #[inline(always)]
833 pub fn is_disable_keep_alive(&self) -> bool {
834 !self.is_enable_keep_alive()
835 }
836}