http_type/request/
impl.rs

1use crate::*;
2
3impl Default for Request {
4    fn default() -> Self {
5        Self {
6            method: Methods::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]
39            .to_string()
40            .parse::<RequestMethod>()
41            .unwrap_or_default();
42        let full_path: RequestPath = parts[1].to_string();
43        let version: RequestVersion = parts[2]
44            .to_string()
45            .parse::<RequestVersion>()
46            .unwrap_or_default();
47        let hash_index: OptionUsize = full_path.find(HASH_SYMBOL);
48        let query_index: OptionUsize = full_path.find(QUERY_SYMBOL);
49        let query_string: String = query_index.map_or(EMPTY_STR.to_owned(), |i| {
50            let temp: String = full_path[i + 1..].to_string();
51            if hash_index.is_none() || hash_index.unwrap() <= i {
52                return temp.into();
53            }
54            let data: String = temp
55                .split(HASH_SYMBOL)
56                .next()
57                .unwrap_or_default()
58                .to_string();
59            data.into()
60        });
61        let querys: RequestQuerys = Self::parse_querys(&query_string);
62        let path: RequestPath = if let Some(i) = query_index.or(hash_index) {
63            full_path[..i].to_string()
64        } else {
65            full_path
66        };
67        let mut headers: RequestHeaders = hash_map_xx_hash3_64();
68        let mut host: RequestHost = EMPTY_STR.to_owned();
69        let mut content_length: usize = 0;
70        loop {
71            let mut header_line: String = String::with_capacity(buffer_size);
72            let _ = AsyncBufReadExt::read_line(reader, &mut header_line).await;
73            let header_line: &str = header_line.trim();
74            if header_line.is_empty() {
75                break;
76            }
77            let parts: Vec<&str> = header_line.splitn(2, COLON_SPACE_SYMBOL).collect();
78            if parts.len() != 2 {
79                continue;
80            }
81            let key: String = parts[0].trim().to_ascii_lowercase();
82            let value: String = parts[1].trim().to_string();
83            if key == HOST {
84                host = value.clone();
85            } else if key == CONTENT_LENGTH {
86                content_length = value.parse().unwrap_or(0);
87            }
88            headers.insert(key, value);
89        }
90        let mut body: RequestBody = vec![0; content_length];
91        if content_length > 0 {
92            let _ = AsyncReadExt::read_exact(reader, &mut body).await;
93        }
94        Ok(Request {
95            method,
96            host,
97            version,
98            path,
99            querys,
100            headers,
101            body,
102        })
103    }
104
105    /// Creates a new `Request` object from a TCP stream.
106    ///
107    /// # Parameters
108    /// - `stream`: A reference to a `&ArcRwLockStream` representing the incoming connection.
109    /// - `buffer_size`: Request buffer size.
110    ///
111    /// # Returns
112    /// - `Ok`: A `Request` object populated with the HTTP request data.
113    /// - `Err`: An `RequestError` if the request is invalid or cannot be read.
114    pub async fn http_request_from_stream(
115        stream: &ArcRwLockStream,
116        buffer_size: usize,
117    ) -> RequestReaderHandleResult {
118        let mut buf_stream: RwLockWriteGuard<'_, TcpStream> = stream.write().await;
119        let mut reader: BufReader<&mut TcpStream> = BufReader::new(&mut buf_stream);
120        Self::http_from_reader(&mut reader, buffer_size).await
121    }
122
123    /// Creates a new `Request` object from a TCP stream.
124    ///
125    /// # Parameters
126    /// - `stream`: A reference to a `&ArcRwLockStream` representing the incoming connection.
127    /// - `buffer_size`: Request buffer size.
128    /// - `request`: A reference to a `Request` object. This object is used as a template.
129    ///
130    /// # Returns
131    /// - `Ok`: A `Request` object populated with the HTTP request data.
132    /// - `Err`: An `RequestError` if the request is invalid or cannot be read.
133    pub async fn websocket_request_from_stream(
134        stream: &ArcRwLockStream,
135        buffer_size: usize,
136        request: &mut Self,
137    ) -> RequestReaderHandleResult {
138        let mut buf_stream: RwLockWriteGuard<'_, TcpStream> = stream.write().await;
139        let mut reader: BufReader<&mut TcpStream> = BufReader::new(&mut buf_stream);
140        Self::websocket_from_reader(&mut reader, buffer_size, request).await
141    }
142
143    /// Reads a WebSocket request from a TCP stream and constructs a `Request` object.
144    ///
145    /// This function reads data from the provided `BufReader` wrapped around a `TcpStream`.
146    /// It attempts to read up to 1024 bytes into a buffer and constructs a `Request` object
147    /// based on the received data. The request body is set using the received bytes.
148    ///
149    /// # Arguments
150    /// - `reader` - A mutable reference to a `BufReader` wrapping a `TcpStream`.
151    ///   This reader is used to read the incoming WebSocket request data.
152    /// - `buffer_size`: - Request buffer size.
153    /// - `request` - A reference to a `Request` object. This object is used as a template.
154    ///
155    /// # Returns
156    /// - `Ok(Request)` - A `Request` object constructed from the received data.
157    ///   - If no data is read (`Ok(0)`), an empty `Request` object is returned.
158    ///   - If data is successfully read, the request body is set with the received bytes.
159    /// - `Err(RequestError::InvalidWebSocketRequest)` - If an error occurs while reading from the stream.
160    pub async fn websocket_from_reader(
161        reader: &mut BufReader<&mut TcpStream>,
162        buffer_size: usize,
163        request: &mut Self,
164    ) -> RequestReaderHandleResult {
165        let mut dynamic_buffer: Vec<u8> = Vec::with_capacity(buffer_size);
166        let mut temp_buffer: Vec<u8> = vec![0; buffer_size];
167        let mut full_frame: Vec<u8> = Vec::with_capacity(buffer_size);
168        let mut error_handle = || {
169            request.body.clear();
170        };
171        loop {
172            let len: usize = match reader.read(&mut temp_buffer).await {
173                Ok(len) => len,
174                Err(err) => {
175                    error_handle();
176                    if err.kind() == ErrorKind::ConnectionReset
177                        || err.kind() == ErrorKind::ConnectionAborted
178                    {
179                        return Err(RequestError::ClientDisconnected);
180                    }
181                    return Err(RequestError::InvalidWebSocketRequest(err.to_string()));
182                }
183            };
184            if len == 0 {
185                error_handle();
186                return Err(RequestError::IncompleteWebSocketFrame);
187            }
188            dynamic_buffer.extend_from_slice(&temp_buffer[..len]);
189            while let Some((frame, consumed)) =
190                WebSocketFrame::decode_websocket_frame_with_length(&dynamic_buffer)
191            {
192                dynamic_buffer.drain(0..consumed);
193                match frame.get_opcode() {
194                    WebSocketOpcode::Close => {
195                        error_handle();
196                        return Err(RequestError::ClientClosedConnection);
197                    }
198                    WebSocketOpcode::Ping | WebSocketOpcode::Pong => {
199                        continue;
200                    }
201                    WebSocketOpcode::Text | WebSocketOpcode::Binary => {
202                        full_frame.extend_from_slice(frame.get_payload_data());
203                        if *frame.get_fin() {
204                            let mut request: Request = request.clone();
205                            request.body = full_frame;
206                            return Ok(request);
207                        }
208                    }
209                    _ => {
210                        error_handle();
211                        return Err(RequestError::InvalidWebSocketFrame(
212                            "Unsupported opcode".into(),
213                        ));
214                    }
215                }
216            }
217        }
218    }
219
220    /// Parse querys
221    ///
222    /// # Parameters
223    /// - `query`: &str
224    ///
225    /// # Returns
226    /// - RequestQuerys
227    fn parse_querys(query: &str) -> RequestQuerys {
228        let mut query_map: RequestQuerys = hash_map_xx_hash3_64();
229        for pair in query.split(AND) {
230            let mut parts: SplitN<'_, &str> = pair.splitn(2, EQUAL);
231            let key: String = parts.next().unwrap_or_default().to_string();
232            if key.is_empty() {
233                continue;
234            }
235            let value: String = parts.next().unwrap_or_default().to_string();
236            query_map.insert(key, value);
237        }
238        query_map
239    }
240
241    /// Retrieves the value of a query parameter by its key.
242    ///
243    /// # Parameters
244    /// - `key`: The query parameter's key, which can be of any type that implements `Into<RequestQuerysKey>`.
245    ///
246    /// # Returns
247    /// - `OptionRequestQuerysValue`: Returns `Some(value)` if the key exists in the query parameters,
248    ///   or `None` if the key does not exist.
249    pub fn get_query<K>(&self, key: K) -> OptionRequestQuerysValue
250    where
251        K: Into<RequestQuerysKey>,
252    {
253        self.querys
254            .get(&key.into())
255            .and_then(|data| Some(data.clone()))
256    }
257
258    /// Retrieves the value of a request header by its key.
259    ///
260    /// # Parameters
261    /// - `key`: The header's key, which can be of any type that implements `Into<RequestHeadersKey>`.
262    ///
263    /// # Returns
264    /// - `OptionRequestHeadersValue`: Returns `Some(value)` if the key exists in the request headers,
265    ///   or `None` if the key does not exist.
266    pub fn get_header<K>(&self, key: K) -> OptionRequestHeadersValue
267    where
268        K: Into<RequestHeadersKey>,
269    {
270        self.headers
271            .get(&key.into())
272            .and_then(|data| Some(data.clone()))
273    }
274
275    /// Retrieves the body content of the object as a UTF-8 encoded string.
276    ///
277    /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` into a string.
278    /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character (�).
279    ///
280    /// # Returns
281    /// A `String` containing the body content.
282    pub fn get_body_string(&self) -> String {
283        String::from_utf8_lossy(self.get_body()).into_owned()
284    }
285
286    /// Deserializes the body content of the object into a specified type `T`.
287    ///
288    /// This method first retrieves the body content as a UTF-8 encoded string using `self.get_body()`.
289    /// It then attempts to deserialize the string into the specified type `T` using `serde_json::from_str`.
290    ///
291    /// # Type Parameters
292    /// - `T`: The target type to deserialize into. It must implement the `DeserializeOwned` trait.
293    ///
294    /// # Returns
295    /// - `Ok(T)`: The deserialized object of type `T` if the deserialization is successful.
296    /// - `Err(serde_json::Error)`: An error if the deserialization fails (e.g., invalid JSON format or type mismatch).
297    pub fn get_body_json<T>(&self) -> ResultSerdeJsonError<T>
298    where
299        T: DeserializeOwned,
300    {
301        serde_json::from_slice(self.get_body())
302    }
303
304    /// Converts the request to a formatted string representation.
305    ///
306    /// - Returns: A `String` containing formatted request details.
307    pub fn get_string(&self) -> String {
308        let body: &Vec<u8> = self.get_body();
309        format!(
310            "[Request] => [Method]: {}; [Host]: {}; [Version]: {}; [Path]: {}; [Querys]: {:?}; [Headers]: {:?}; [Body]: {};",
311            self.get_method(),
312            self.get_host(),
313            self.get_version(),
314            self.get_path(),
315            self.get_querys(),
316            self.get_headers(),
317            match std::str::from_utf8(body) {
318                Ok(string_data) => Cow::Borrowed(string_data),
319                Err(_) => Cow::Owned(format!("binary data len: {}", body.len())),
320            },
321        )
322    }
323
324    /// Retrieves the upgrade type from the request headers.
325    ///
326    /// - Returns: The `UpgradeType` extracted from the `UPGRADE` header.
327    ///            If the header is missing or invalid, returns the default `UpgradeType`.
328    pub fn get_upgrade_type(&self) -> UpgradeType {
329        let upgrade_type: UpgradeType = self
330            .get_header(UPGRADE)
331            .and_then(|data| data.parse::<UpgradeType>().ok())
332            .unwrap_or_default();
333        upgrade_type
334    }
335
336    /// Checks whether the WebSocket upgrade is enabled.
337    ///
338    /// - Returns: `true` if the upgrade type is WebSocket; otherwise, `false`.
339    pub fn upgrade_type_is_websocket(&self) -> bool {
340        self.get_upgrade_type().is_websocket()
341    }
342
343    /// Checks whether the upgrade type is HTTP.
344    ///
345    /// - Returns: `true` if the upgrade type is HTTP; otherwise, `false`.
346    pub fn upgrade_type_is_http(&self) -> bool {
347        self.get_upgrade_type().is_http()
348    }
349
350    /// Checks whether the upgrade type is unknown.
351    ///
352    /// - Returns: `true` if the upgrade type is unknown; otherwise, `false`.
353    pub fn upgrade_type_is_unknown(&self) -> bool {
354        self.get_upgrade_type().is_unknown()
355    }
356
357    /// Checks if the HTTP version is HTTP/1.1 or higher.
358    ///
359    /// - Returns: `true` if the HTTP version is 1.1 or higher; otherwise, `false`.
360    pub fn version_is_http1_1_or_higher(&self) -> bool {
361        self.get_version().is_http1_1_or_higher()
362    }
363
364    /// Checks whether the HTTP version is HTTP/0.9.
365    ///
366    /// - Returns: `true` if the version is HTTP/0.9; otherwise, `false`.
367    pub fn version_is_http0_9(&self) -> bool {
368        self.get_version().is_http0_9()
369    }
370
371    /// Checks whether the HTTP version is HTTP/1.0.
372    ///
373    /// - Returns: `true` if the version is HTTP/1.0; otherwise, `false`.
374    pub fn version_is_http1_0(&self) -> bool {
375        self.get_version().is_http1_0()
376    }
377
378    /// Checks whether the HTTP version is HTTP/1.1.
379    ///
380    /// - Returns: `true` if the version is HTTP/1.1; otherwise, `false`.
381    pub fn version_is_http1_1(&self) -> bool {
382        self.get_version().is_http1_1()
383    }
384
385    /// Checks whether the HTTP version is HTTP/2.
386    ///
387    /// - Returns: `true` if the version is HTTP/2; otherwise, `false`.
388    pub fn version_is_http2(&self) -> bool {
389        self.get_version().is_http2()
390    }
391
392    /// Checks whether the HTTP version is HTTP/3.
393    ///
394    /// - Returns: `true` if the version is HTTP/3; otherwise, `false`.
395    pub fn version_is_http3(&self) -> bool {
396        self.get_version().is_http3()
397    }
398
399    /// Checks whether the HTTP version is unknown.
400    ///
401    /// - Returns: `true` if the version is unknown; otherwise, `false`.
402    pub fn version_is_unknown(&self) -> bool {
403        self.get_version().is_unknown()
404    }
405
406    /// Checks whether the version belongs to the HTTP family.
407    ///
408    /// - Returns: `true` if the version is a valid HTTP version; otherwise, `false`.
409    pub fn version_is_http(&self) -> bool {
410        self.get_version().is_http()
411    }
412
413    /// Checks whether the request method is `GET`.
414    ///
415    /// - Returns: `true` if the method is `GET`; otherwise, `false`.
416    pub fn method_is_get(&self) -> bool {
417        self.get_method().is_get()
418    }
419
420    /// Checks whether the request method is `POST`.
421    ///
422    /// - Returns: `true` if the method is `POST`; otherwise, `false`.
423    pub fn method_is_post(&self) -> bool {
424        self.get_method().is_post()
425    }
426
427    /// Checks whether the request method is `PUT`.
428    ///
429    /// - Returns: `true` if the method is `PUT`; otherwise, `false`.
430    pub fn method_is_put(&self) -> bool {
431        self.get_method().is_put()
432    }
433
434    /// Checks whether the request method is `DELETE`.
435    ///
436    /// - Returns: `true` if the method is `DELETE`; otherwise, `false`.
437    pub fn method_is_delete(&self) -> bool {
438        self.get_method().is_delete()
439    }
440
441    /// Checks whether the request method is `PATCH`.
442    ///
443    /// - Returns: `true` if the method is `PATCH`; otherwise, `false`.
444    pub fn method_is_patch(&self) -> bool {
445        self.get_method().is_patch()
446    }
447
448    /// Checks whether the request method is `HEAD`.
449    ///
450    /// - Returns: `true` if the method is `HEAD`; otherwise, `false`.
451    pub fn method_is_head(&self) -> bool {
452        self.get_method().is_head()
453    }
454
455    /// Checks whether the request method is `OPTIONS`.
456    ///
457    /// - Returns: `true` if the method is `OPTIONS`; otherwise, `false`.
458    pub fn method_is_options(&self) -> bool {
459        self.get_method().is_options()
460    }
461
462    /// Checks whether the request method is `CONNECT`.
463    ///
464    /// - Returns: `true` if the method is `CONNECT`; otherwise, `false`.
465    pub fn method_is_connect(&self) -> bool {
466        self.get_method().is_connect()
467    }
468
469    /// Checks whether the request method is `TRACE`.
470    ///
471    /// - Returns: `true` if the method is `TRACE`; otherwise, `false`.
472    pub fn method_is_trace(&self) -> bool {
473        self.get_method().is_trace()
474    }
475
476    /// Checks whether the request method is `UNKNOWN`.
477    ///
478    /// - Returns: `true` if the method is `UNKNOWN`; otherwise, `false`.
479    pub fn method_is_unknown(&self) -> bool {
480        self.get_method().is_unknown()
481    }
482
483    /// Determines if keep-alive connection should be enabled for this request.
484    ///
485    /// This function checks the Connection header and HTTP version to determine if
486    /// keep-alive should be enabled. The logic is as follows:
487    ///
488    /// 1. If Connection header exists:
489    ///    - Returns true if header value is "keep-alive"
490    ///    - Returns false if header value is "close"
491    /// 2. If no Connection header:
492    ///    - Returns true if HTTP version is 1.1 or higher
493    ///    - Returns false otherwise
494    ///
495    /// # Returns
496    /// - `bool`: true if keep-alive should be enabled, false otherwise
497    pub fn is_enable_keep_alive(&self) -> bool {
498        if let Some(connection_value) = self.get_header(CONNECTION) {
499            let connection_value_lowercase: String = connection_value.to_ascii_lowercase();
500            if connection_value_lowercase == CONNECTION_KEEP_ALIVE {
501                return true;
502            } else if connection_value_lowercase == CONNECTION_CLOSE {
503                return self.upgrade_type_is_websocket();
504            }
505        }
506        self.version_is_http1_1_or_higher() || self.upgrade_type_is_websocket()
507    }
508}