http_type/request/
impl.rs

1use crate::*;
2
3impl Default for Request {
4    fn default() -> Self {
5        Self {
6            method: Method::default(),
7            host: String::new(),
8            version: HttpVersion::default(),
9            path: String::new(),
10            querys: hash_map_xx_hash3_64(),
11            headers: hash_map_xx_hash3_64(),
12            body: Vec::new(),
13        }
14    }
15}
16
17impl Request {
18    /// Creates a new `Request` object from a TCP stream.
19    ///
20    /// # Parameters
21    /// - `reader`: A mut reference to a `&mut BufReader<&mut TcpStream>`.
22    /// - `buffer_size`: Request buffer size.
23    ///
24    /// # Returns
25    /// - `Ok`: A `Request` object populated with the HTTP request data.
26    /// - `Err`: An `RequestError` if the request is invalid or cannot be read.
27    pub async fn http_from_reader(
28        reader: &mut BufReader<&mut TcpStream>,
29        buffer_size: usize,
30    ) -> RequestReaderHandleResult {
31        let mut request_line: String = String::with_capacity(buffer_size);
32        let _ = AsyncBufReadExt::read_line(reader, &mut request_line).await;
33        let parts: Vec<&str> = request_line.split_whitespace().collect();
34        let parts_len: usize = parts.len();
35        if parts_len < 3 {
36            return Err(RequestError::InvalidHttpRequestPartsLength(parts_len));
37        }
38        let method: RequestMethod = parts[0].parse::<RequestMethod>().unwrap_or_default();
39        let full_path: RequestPath = parts[1].to_string();
40        let version: RequestVersion = parts[2].parse::<RequestVersion>().unwrap_or_default();
41        let hash_index: OptionUsize = full_path.find(HASH_SYMBOL);
42        let query_index: OptionUsize = full_path.find(QUERY_SYMBOL);
43        let query_string: String = query_index.map_or(String::new(), |i| {
44            let temp: &str = &full_path[i + 1..];
45            if hash_index.is_none() || hash_index.unwrap() <= i {
46                return temp.to_string();
47            }
48            temp.split(HASH_SYMBOL)
49                .next()
50                .unwrap_or_default()
51                .to_string()
52        });
53        let querys: RequestQuerys = Self::parse_querys(&query_string);
54        let path: RequestPath = if let Some(i) = query_index.or(hash_index) {
55            full_path[..i].to_string()
56        } else {
57            full_path
58        };
59        let mut headers: RequestHeaders = hash_map_xx_hash3_64();
60        let mut host: RequestHost = String::new();
61        let mut content_length: usize = 0;
62        loop {
63            let mut header_line: String = String::with_capacity(buffer_size);
64            let _ = AsyncBufReadExt::read_line(reader, &mut header_line).await;
65            let header_line: &str = header_line.trim();
66            if header_line.is_empty() {
67                break;
68            }
69            if let Some((key_part, value_part)) = header_line.split_once(COLON_SPACE_SYMBOL) {
70                let key: String = key_part.trim().to_ascii_lowercase();
71                if key.is_empty() {
72                    continue;
73                }
74                let value: String = value_part.trim().to_string();
75                if key == HOST {
76                    host = value.clone();
77                } else if key == CONTENT_LENGTH {
78                    content_length = value.parse().unwrap_or(0);
79                }
80                headers
81                    .entry(key)
82                    .or_insert_with(VecDeque::new)
83                    .push_back(value);
84            }
85        }
86        let mut body: RequestBody = vec![0; content_length];
87        if content_length > 0 {
88            let _ = AsyncReadExt::read_exact(reader, &mut body).await;
89        }
90        Ok(Request {
91            method,
92            host,
93            version,
94            path,
95            querys,
96            headers,
97            body,
98        })
99    }
100
101    /// Creates a new `Request` object from a TCP stream.
102    ///
103    /// # Parameters
104    /// - `stream`: A reference to a `&ArcRwLockStream` representing the incoming connection.
105    /// - `buffer_size`: Request buffer size.
106    ///
107    /// # Returns
108    /// - `Ok`: A `Request` object populated with the HTTP request data.
109    /// - `Err`: An `RequestError` if the request is invalid or cannot be read.
110    pub async fn http_request_from_stream(
111        stream: &ArcRwLockStream,
112        buffer_size: usize,
113    ) -> RequestReaderHandleResult {
114        let mut buf_stream: RwLockWriteGuard<'_, TcpStream> = stream.write().await;
115        let mut reader: BufReader<&mut TcpStream> = BufReader::new(&mut buf_stream);
116        Self::http_from_reader(&mut reader, buffer_size).await
117    }
118
119    /// Creates a new `Request` object from a TCP stream.
120    ///
121    /// # Parameters
122    /// - `stream`: A reference to a `&ArcRwLockStream` representing the incoming connection.
123    /// - `buffer_size`: Request buffer size.
124    /// - `request`: A reference to a `Request` object. This object is used as a template.
125    ///
126    /// # Returns
127    /// - `Ok`: A `Request` object populated with the HTTP request data.
128    /// - `Err`: An `RequestError` if the request is invalid or cannot be read.
129    pub async fn ws_request_from_stream(
130        stream: &ArcRwLockStream,
131        buffer_size: usize,
132        request: &mut Self,
133    ) -> RequestReaderHandleResult {
134        let mut buf_stream: RwLockWriteGuard<'_, TcpStream> = stream.write().await;
135        let mut reader: BufReader<&mut TcpStream> = BufReader::new(&mut buf_stream);
136        Self::ws_from_reader(&mut reader, buffer_size, request).await
137    }
138
139    /// Reads a WebSocket request from a TCP stream and constructs a `Request` object.
140    ///
141    /// This function reads data from the provided `BufReader` wrapped around a `TcpStream`.
142    /// It attempts to read up to 1024 bytes into a buffer and constructs a `Request` object
143    /// based on the received data. The request body is set using the received bytes.
144    ///
145    /// # Arguments
146    /// - `reader` - A mutable reference to a `BufReader` wrapping a `TcpStream`.
147    ///   This reader is used to read the incoming WebSocket request data.
148    /// - `buffer_size`: - Request buffer size.
149    /// - `request` - A reference to a `Request` object. This object is used as a template.
150    ///
151    /// # Returns
152    /// - `Ok(Request)` - A `Request` object constructed from the received data.
153    ///   - If no data is read (`Ok(0)`), an empty `Request` object is returned.
154    ///   - If data is successfully read, the request body is set with the received bytes.
155    /// - `Err(RequestError::InvalidWebSocketRequest)` - If an error occurs while reading from the stream.
156    pub async fn ws_from_reader(
157        reader: &mut BufReader<&mut TcpStream>,
158        buffer_size: usize,
159        request: &mut Self,
160    ) -> RequestReaderHandleResult {
161        let mut dynamic_buffer: Vec<u8> = Vec::with_capacity(buffer_size);
162        let mut temp_buffer: Vec<u8> = vec![0; buffer_size];
163        let mut full_frame: Vec<u8> = Vec::new();
164        let mut error_handle = || {
165            request.body.clear();
166        };
167        loop {
168            let len: usize = match reader.read(&mut temp_buffer).await {
169                Ok(len) => len,
170                Err(err) => {
171                    error_handle();
172                    if err.kind() == ErrorKind::ConnectionReset
173                        || err.kind() == ErrorKind::ConnectionAborted
174                    {
175                        return Err(RequestError::ClientDisconnected);
176                    }
177                    return Err(RequestError::InvalidWebSocketRequest(err.to_string()));
178                }
179            };
180            if len == 0 {
181                error_handle();
182                return Err(RequestError::IncompleteWebSocketFrame);
183            }
184            dynamic_buffer.extend_from_slice(&temp_buffer[..len]);
185            while let Some((frame, consumed)) = WebSocketFrame::decode_ws_frame(&dynamic_buffer) {
186                dynamic_buffer.drain(0..consumed);
187                match frame.get_opcode() {
188                    WebSocketOpcode::Close => {
189                        error_handle();
190                        return Err(RequestError::ClientClosedConnection);
191                    }
192                    WebSocketOpcode::Ping | WebSocketOpcode::Pong => {
193                        continue;
194                    }
195                    WebSocketOpcode::Text | WebSocketOpcode::Binary => {
196                        full_frame.extend_from_slice(frame.get_payload_data());
197                        if *frame.get_fin() {
198                            let mut request: Request = request.clone();
199                            request.body = full_frame;
200                            return Ok(request);
201                        }
202                    }
203                    _ => {
204                        error_handle();
205                        return Err(RequestError::InvalidWebSocketFrame(
206                            "Unsupported opcode".into(),
207                        ));
208                    }
209                }
210            }
211        }
212    }
213
214    /// Parse querys
215    ///
216    /// # Parameters
217    /// - `query`: &str
218    ///
219    /// # Returns
220    /// - RequestQuerys
221    fn parse_querys(query: &str) -> RequestQuerys {
222        let mut query_map: RequestQuerys = hash_map_xx_hash3_64();
223        for pair in query.split(AND) {
224            if let Some((key, value)) = pair.split_once(EQUAL) {
225                if !key.is_empty() {
226                    query_map.insert(key.to_string(), value.to_string());
227                }
228            } else if !pair.is_empty() {
229                query_map.insert(pair.to_string(), String::new());
230            }
231        }
232        query_map
233    }
234
235    /// Retrieves the value of a query parameter by its key.
236    ///
237    /// # Parameters
238    /// - `key`: The query parameter's key, which can be of any type that implements `Into<RequestQuerysKey>`.
239    ///
240    /// # Returns
241    /// - `OptionRequestQuerysValue`: Returns `Some(value)` if the key exists in the query parameters,
242    ///   or `None` if the key does not exist.
243    pub fn get_query<K>(&self, key: K) -> OptionRequestQuerysValue
244    where
245        K: Into<RequestQuerysKey>,
246    {
247        self.querys.get(&key.into()).cloned()
248    }
249
250    /// Retrieves the value of a request query parameter by its key.
251    ///
252    /// # Parameters
253    /// - `key`: The query parameter's key, which can be of any type that implements `Into<RequestHeadersKey>`.
254    ///
255    /// # Returns
256    /// - `OptionRequestQuerysValue`: Returns `Some(value)` if the key exists in the query parameters,
257    ///   or `None` if the key does not exist.
258    pub fn get_request_query<T>(&self, key: T) -> OptionRequestQuerysValue
259    where
260        T: Into<RequestHeadersKey>,
261    {
262        self.querys.get(&key.into()).map(|data| data.clone())
263    }
264
265    /// Retrieves the value of a request header by its key.
266    ///
267    /// # Parameters
268    /// - `key`: The header's key, which can be of any type that implements `Into<RequestHeadersKey>`.
269    ///
270    /// # Returns
271    /// - `OptionRequestHeadersValue`: Returns `Some(value)` if the key exists in the request headers,
272    ///   or `None` if the key does not exist.
273    pub fn get_header<K>(&self, key: K) -> OptionRequestHeadersValue
274    where
275        K: Into<RequestHeadersKey>,
276    {
277        self.headers.get(&key.into()).cloned()
278    }
279
280    /// Retrieves the first value of a request header by its key.
281    ///
282    /// # Parameters
283    /// - `key`: The header's key, which can be of any type that implements `Into<RequestHeadersKey>`.
284    ///
285    /// # Returns
286    /// - `OptionRequestHeadersValueItem`: Returns `Some(value)` if the key exists and has at least one value,
287    ///   or `None` if the key does not exist or has no values.
288    pub fn get_header_front<K>(&self, key: K) -> OptionRequestHeadersValueItem
289    where
290        K: Into<RequestHeadersKey>,
291    {
292        self.headers
293            .get(&key.into())
294            .and_then(|values| values.front().cloned())
295    }
296
297    /// Retrieves the last value of a request header by its key.
298    ///
299    /// # Parameters
300    /// - `key`: The header's key, which can be of any type that implements `Into<RequestHeadersKey>`.
301    ///
302    /// # Returns
303    /// - `OptionRequestHeadersValueItem`: Returns `Some(value)` if the key exists and has at least one value,
304    ///   or `None` if the key does not exist or has no values.
305    pub fn get_header_back<K>(&self, key: K) -> OptionRequestHeadersValueItem
306    where
307        K: Into<RequestHeadersKey>,
308    {
309        self.headers
310            .get(&key.into())
311            .and_then(|values| values.back().cloned())
312    }
313
314    /// Retrieves the number of values for a specific header.
315    ///
316    /// # Parameters
317    /// - `key`: The header's key, which can be of any type that implements `Into<RequestHeadersKey>`.
318    ///
319    /// # Returns
320    /// - `usize`: The number of values for the specified header. Returns 0 if the header does not exist.
321    pub fn get_header_len<K>(&self, key: K) -> usize
322    where
323        K: Into<RequestHeadersKey>,
324    {
325        self.headers
326            .get(&key.into())
327            .map(|values| values.len())
328            .unwrap_or(0)
329    }
330
331    /// Retrieves the total number of header values across all headers.
332    ///
333    /// # Returns
334    /// - `usize`: The total count of all header values.
335    pub fn get_headers_values_len(&self) -> usize {
336        self.headers.values().map(|values| values.len()).sum()
337    }
338
339    /// Retrieves the number of unique headers.
340    ///
341    /// # Returns
342    /// - `usize`: The number of unique header keys.
343    pub fn get_headers_len(&self) -> usize {
344        self.headers.len()
345    }
346
347    /// Checks if a specific header exists.
348    ///
349    /// # Parameters
350    /// - `key`: The header key to check, which will be converted into a `RequestHeadersKey`.
351    ///
352    /// # Returns
353    /// - `bool`: Returns `true` if the header exists, `false` otherwise.
354    pub fn has_header<K>(&self, key: K) -> bool
355    where
356        K: Into<RequestHeadersKey>,
357    {
358        self.headers.contains_key(&key.into())
359    }
360
361    /// Checks if a header contains a specific value.
362    ///
363    /// # Parameters
364    /// - `key`: The header key to check, which will be converted into a `RequestHeadersKey`.
365    /// - `value`: The value to search for in the header.
366    ///
367    /// # Returns
368    /// - `bool`: Returns `true` if the header exists and contains the specified value, `false` otherwise.
369    pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
370    where
371        K: Into<RequestHeadersKey>,
372        V: Into<RequestHeadersValueItem>,
373    {
374        let key: RequestHeadersKey = key.into();
375        let value: RequestHeadersValueItem = value.into();
376        if let Some(values) = self.headers.get(&key) {
377            values.contains(&value)
378        } else {
379            false
380        }
381    }
382
383    /// Retrieves the body content of the object as a UTF-8 encoded string.
384    ///
385    /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` into a string.
386    /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character (�).
387    ///
388    /// # Returns
389    /// A `String` containing the body content.
390    pub fn get_body_string(&self) -> String {
391        String::from_utf8_lossy(self.get_body()).into_owned()
392    }
393
394    /// Deserializes the body content of the object into a specified type `T`.
395    ///
396    /// This method first retrieves the body content as a UTF-8 encoded string using `self.get_body()`.
397    /// It then attempts to deserialize the string into the specified type `T` using `json_from_slice`.
398    ///
399    /// # Type Parameters
400    /// - `T`: The target type to deserialize into. It must implement the `DeserializeOwned` trait.
401    ///
402    /// # Returns
403    /// - `Ok(T)`: The deserialized object of type `T` if the deserialization is successful.
404    /// - `Err(ResultJsonError)`: An error if the deserialization fails (e.g., invalid JSON format or type mismatch).
405    pub fn get_body_json<T>(&self) -> ResultJsonError<T>
406    where
407        T: DeserializeOwned,
408    {
409        json_from_slice(self.get_body())
410    }
411
412    /// Converts the request to a formatted string representation.
413    ///
414    /// - Returns: A `String` containing formatted request details.
415    pub fn get_string(&self) -> String {
416        let body: &Vec<u8> = self.get_body();
417        let body_type: &'static str = if std::str::from_utf8(body).is_ok() {
418            PLAIN
419        } else {
420            BINARY
421        };
422        format!(
423            "[Request] => [method]: {}; [host]: {}; [version]: {}; [path]: {}; [querys]: {:?}; [headers]: {:?}; [body]: {} bytes {};",
424            self.get_method(),
425            self.get_host(),
426            self.get_version(),
427            self.get_path(),
428            self.get_querys(),
429            self.get_headers(),
430            body.len(),
431            body_type
432        )
433    }
434
435    /// Retrieves the upgrade type from the request headers.
436    ///
437    /// - Returns: The `UpgradeType` extracted from the `UPGRADE` header.
438    ///            If the header is missing or invalid, returns the default `UpgradeType`.
439    pub fn get_upgrade_type(&self) -> UpgradeType {
440        let upgrade_type: UpgradeType = self
441            .get_header_back(UPGRADE)
442            .and_then(|data| data.parse::<UpgradeType>().ok())
443            .unwrap_or_default();
444        upgrade_type
445    }
446
447    /// Checks whether the WebSocket upgrade is enabled.
448    ///
449    /// - Returns: `true` if the upgrade type is WebSocket; otherwise, `false`.
450    pub fn is_ws(&self) -> bool {
451        self.get_upgrade_type().is_ws()
452    }
453
454    /// Checks if the current upgrade type is HTTP/2 cleartext (h2c).
455    ///
456    /// - `&self` - The current instance (usually a request or context struct).
457    ///
458    /// - Returns `true` if the upgrade type is `h2c`, otherwise `false`.
459    pub fn is_h2c(&self) -> bool {
460        self.get_upgrade_type().is_h2c()
461    }
462
463    /// Checks if the current upgrade type is TLS (any version).
464    ///
465    /// - `&self` - The current instance (usually a request or context struct).
466    ///
467    /// - Returns `true` if the upgrade type is any `Tls` variant, otherwise `false`.
468    pub fn is_tls(&self) -> bool {
469        self.get_upgrade_type().is_tls()
470    }
471
472    /// Checks whether the upgrade type is unknown.
473    ///
474    /// - Returns: `true` if the upgrade type is unknown; otherwise, `false`.
475    pub fn is_unknown_upgrade(&self) -> bool {
476        self.get_upgrade_type().is_unknown()
477    }
478
479    /// Checks if the HTTP version is HTTP/1.1 or higher.
480    ///
481    /// - Returns: `true` if the HTTP version is 1.1 or higher; otherwise, `false`.
482    pub fn is_http1_1_or_higher(&self) -> bool {
483        self.get_version().is_http1_1_or_higher()
484    }
485
486    /// Checks whether the HTTP version is HTTP/0.9.
487    ///
488    /// - Returns: `true` if the version is HTTP/0.9; otherwise, `false`.
489    pub fn is_http0_9(&self) -> bool {
490        self.get_version().is_http0_9()
491    }
492
493    /// Checks whether the HTTP version is HTTP/1.0.
494    ///
495    /// - Returns: `true` if the version is HTTP/1.0; otherwise, `false`.
496    pub fn is_http1_0(&self) -> bool {
497        self.get_version().is_http1_0()
498    }
499
500    /// Checks whether the HTTP version is HTTP/1.1.
501    ///
502    /// - Returns: `true` if the version is HTTP/1.1; otherwise, `false`.
503    pub fn is_http1_1(&self) -> bool {
504        self.get_version().is_http1_1()
505    }
506
507    /// Checks whether the HTTP version is HTTP/2.
508    ///
509    /// - Returns: `true` if the version is HTTP/2; otherwise, `false`.
510    pub fn is_http2(&self) -> bool {
511        self.get_version().is_http2()
512    }
513
514    /// Checks whether the HTTP version is HTTP/3.
515    ///
516    /// - Returns: `true` if the version is HTTP/3; otherwise, `false`.
517    pub fn is_http3(&self) -> bool {
518        self.get_version().is_http3()
519    }
520
521    /// Checks whether the HTTP version is unknown.
522    ///
523    /// - Returns: `true` if the version is unknown; otherwise, `false`.
524    pub fn is_unknown_version(&self) -> bool {
525        self.get_version().is_unknown()
526    }
527
528    /// Checks whether the version belongs to the HTTP family.
529    ///
530    /// - Returns: `true` if the version is a valid HTTP version; otherwise, `false`.
531    pub fn is_http(&self) -> bool {
532        self.get_version().is_http()
533    }
534
535    /// Checks whether the request method is `GET`.
536    ///
537    /// - Returns: `true` if the method is `GET`; otherwise, `false`.
538    pub fn is_get(&self) -> bool {
539        self.get_method().is_get()
540    }
541
542    /// Checks whether the request method is `POST`.
543    ///
544    /// - Returns: `true` if the method is `POST`; otherwise, `false`.
545    pub fn is_post(&self) -> bool {
546        self.get_method().is_post()
547    }
548
549    /// Checks whether the request method is `PUT`.
550    ///
551    /// - Returns: `true` if the method is `PUT`; otherwise, `false`.
552    pub fn is_put(&self) -> bool {
553        self.get_method().is_put()
554    }
555
556    /// Checks whether the request method is `DELETE`.
557    ///
558    /// - Returns: `true` if the method is `DELETE`; otherwise, `false`.
559    pub fn is_delete(&self) -> bool {
560        self.get_method().is_delete()
561    }
562
563    /// Checks whether the request method is `PATCH`.
564    ///
565    /// - Returns: `true` if the method is `PATCH`; otherwise, `false`.
566    pub fn is_patch(&self) -> bool {
567        self.get_method().is_patch()
568    }
569
570    /// Checks whether the request method is `HEAD`.
571    ///
572    /// - Returns: `true` if the method is `HEAD`; otherwise, `false`.
573    pub fn is_head(&self) -> bool {
574        self.get_method().is_head()
575    }
576
577    /// Checks whether the request method is `OPTIONS`.
578    ///
579    /// - Returns: `true` if the method is `OPTIONS`; otherwise, `false`.
580    pub fn is_options(&self) -> bool {
581        self.get_method().is_options()
582    }
583
584    /// Checks whether the request method is `CONNECT`.
585    ///
586    /// - Returns: `true` if the method is `CONNECT`; otherwise, `false`.
587    pub fn is_connect(&self) -> bool {
588        self.get_method().is_connect()
589    }
590
591    /// Checks whether the request method is `TRACE`.
592    ///
593    /// - Returns: `true` if the method is `TRACE`; otherwise, `false`.
594    pub fn is_trace(&self) -> bool {
595        self.get_method().is_trace()
596    }
597
598    /// Checks whether the request method is `UNKNOWN`.
599    ///
600    /// - Returns: `true` if the method is `UNKNOWN`; otherwise, `false`.
601    pub fn is_unknown_method(&self) -> bool {
602        self.get_method().is_unknown()
603    }
604
605    /// Determines if keep-alive connection should be enabled for this request.
606    ///
607    /// This function checks the Connection header and HTTP version to determine if
608    /// keep-alive should be enabled. The logic is as follows:
609    ///
610    /// 1. If Connection header exists:
611    ///    - Returns true if header value is "keep-alive"
612    ///    - Returns false if header value is "close"
613    /// 2. If no Connection header:
614    ///    - Returns true if HTTP version is 1.1 or higher
615    ///    - Returns false otherwise
616    ///
617    /// # Returns
618    /// - `bool`: true if keep-alive should be enabled, false otherwise
619    pub fn is_enable_keep_alive(&self) -> bool {
620        if let Some(connection_value) = self.get_header_back(CONNECTION) {
621            if connection_value.eq_ignore_ascii_case(KEEP_ALIVE) {
622                return true;
623            } else if connection_value.eq_ignore_ascii_case(CLOSE) {
624                return self.is_ws();
625            }
626        }
627        self.is_http1_1_or_higher() || self.is_ws()
628    }
629}