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.get_write_lock().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: &Self,
137    ) -> RequestReaderHandleResult {
138        let mut buf_stream: RwLockWriteGuard<'_, TcpStream> = stream.get_write_lock().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: &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        loop {
169            let len: usize = match reader.read(&mut temp_buffer).await {
170                Ok(len) => len,
171                Err(err) => return Err(RequestError::InvalidWebSocketRequest(err.to_string())),
172            };
173            if len == 0 {
174                break;
175            }
176            dynamic_buffer.extend_from_slice(&temp_buffer[..len]);
177            if let Some((frame, consumed)) =
178                WebSocketFrame::decode_websocket_frame_with_length(&dynamic_buffer)
179            {
180                dynamic_buffer.drain(0..consumed);
181                full_frame.extend_from_slice(frame.get_payload_data());
182                if *frame.get_fin() {
183                    let mut request: Request = request.clone();
184                    request.body = full_frame;
185                    return Ok(request);
186                }
187            }
188        }
189        Err(RequestError::WebSocketRead)
190    }
191
192    /// Parse querys
193    ///
194    /// # Parameters
195    /// - `query`: &str
196    ///
197    /// # Returns
198    /// - RequestQuerys
199    fn parse_querys(query: &str) -> RequestQuerys {
200        let mut query_map: RequestQuerys = hash_map_xx_hash3_64();
201        for pair in query.split(AND) {
202            let mut parts: SplitN<'_, &str> = pair.splitn(2, EQUAL);
203            let key: String = parts.next().unwrap_or_default().to_string();
204            if key.is_empty() {
205                continue;
206            }
207            let value: String = parts.next().unwrap_or_default().to_string();
208            query_map.insert(key, value);
209        }
210        query_map
211    }
212
213    /// Retrieves the value of a query parameter by its key.
214    ///
215    /// # Parameters
216    /// - `key`: The query parameter's key, which can be of any type that implements `Into<RequestQuerysKey>`.
217    ///
218    /// # Returns
219    /// - `OptionRequestQuerysValue`: Returns `Some(value)` if the key exists in the query parameters,
220    ///   or `None` if the key does not exist.
221    pub fn get_query<K>(&self, key: K) -> OptionRequestQuerysValue
222    where
223        K: Into<RequestQuerysKey>,
224    {
225        self.querys
226            .get(&key.into())
227            .and_then(|data| Some(data.clone()))
228    }
229
230    /// Retrieves the value of a request header by its key.
231    ///
232    /// # Parameters
233    /// - `key`: The header's key, which can be of any type that implements `Into<RequestHeadersKey>`.
234    ///
235    /// # Returns
236    /// - `OptionRequestHeadersValue`: Returns `Some(value)` if the key exists in the request headers,
237    ///   or `None` if the key does not exist.
238    pub fn get_header<K>(&self, key: K) -> OptionRequestHeadersValue
239    where
240        K: Into<RequestHeadersKey>,
241    {
242        self.headers
243            .get(&key.into())
244            .and_then(|data| Some(data.clone()))
245    }
246
247    /// Retrieves the body content of the object as a UTF-8 encoded string.
248    ///
249    /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` into a string.
250    /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character (�).
251    ///
252    /// # Returns
253    /// A `String` containing the body content.
254    pub fn get_body_string(&self) -> String {
255        String::from_utf8_lossy(self.get_body()).into_owned()
256    }
257
258    /// Deserializes the body content of the object into a specified type `T`.
259    ///
260    /// This method first retrieves the body content as a UTF-8 encoded string using `self.get_body()`.
261    /// It then attempts to deserialize the string into the specified type `T` using `serde_json::from_str`.
262    ///
263    /// # Type Parameters
264    /// - `T`: The target type to deserialize into. It must implement the `DeserializeOwned` trait.
265    ///
266    /// # Returns
267    /// - `Ok(T)`: The deserialized object of type `T` if the deserialization is successful.
268    /// - `Err(serde_json::Error)`: An error if the deserialization fails (e.g., invalid JSON format or type mismatch).
269    pub fn get_body_json<T>(&self) -> ResultSerdeJsonError<T>
270    where
271        T: DeserializeOwned,
272    {
273        serde_json::from_slice(self.get_body())
274    }
275
276    /// Converts the request to a formatted string representation.
277    ///
278    /// - Returns: A `String` containing formatted request details.
279    pub fn get_string(&self) -> String {
280        let body: &Vec<u8> = self.get_body();
281        format!(
282            "[Request] => [Method]: {}; [Host]: {}; [Version]: {}; [Path]: {}; [Querys]: {:?}; [Headers]: {:?}; [Body]: {};",
283            self.get_method(),
284            self.get_host(),
285            self.get_version(),
286            self.get_path(),
287            self.get_querys(),
288            self.get_headers(),
289            match std::str::from_utf8(body) {
290                Ok(string_data) => Cow::Borrowed(string_data),
291                Err(_) => Cow::Owned(format!("binary data len: {}", body.len())),
292            },
293        )
294    }
295
296    /// Retrieves the upgrade type from the request headers.
297    ///
298    /// - Returns: The `UpgradeType` extracted from the `UPGRADE` header.
299    ///            If the header is missing or invalid, returns the default `UpgradeType`.
300    pub fn get_upgrade_type(&self) -> UpgradeType {
301        let upgrade_type: UpgradeType = self
302            .get_header(UPGRADE)
303            .and_then(|data| data.parse::<UpgradeType>().ok())
304            .unwrap_or_default();
305        upgrade_type
306    }
307
308    /// Checks whether the WebSocket upgrade is enabled.
309    ///
310    /// - Returns: `true` if the upgrade type is WebSocket; otherwise, `false`.
311    pub fn upgrade_type_is_websocket(&self) -> bool {
312        self.get_upgrade_type().is_websocket()
313    }
314
315    /// Checks whether the upgrade type is HTTP.
316    ///
317    /// - Returns: `true` if the upgrade type is HTTP; otherwise, `false`.
318    pub fn upgrade_type_is_http(&self) -> bool {
319        self.get_upgrade_type().is_http()
320    }
321
322    /// Checks whether the upgrade type is unknown.
323    ///
324    /// - Returns: `true` if the upgrade type is unknown; otherwise, `false`.
325    pub fn upgrade_type_is_unknown(&self) -> bool {
326        self.get_upgrade_type().is_unknown()
327    }
328
329    /// Checks if the HTTP version is HTTP/1.1 or higher.
330    ///
331    /// - Returns: `true` if the HTTP version is 1.1 or higher; otherwise, `false`.
332    pub fn version_is_http1_1_or_higher(&self) -> bool {
333        self.get_version().is_http1_1_or_higher()
334    }
335
336    /// Checks whether the HTTP version is HTTP/0.9.
337    ///
338    /// - Returns: `true` if the version is HTTP/0.9; otherwise, `false`.
339    pub fn version_is_http0_9(&self) -> bool {
340        self.get_version().is_http0_9()
341    }
342
343    /// Checks whether the HTTP version is HTTP/1.0.
344    ///
345    /// - Returns: `true` if the version is HTTP/1.0; otherwise, `false`.
346    pub fn version_is_http1_0(&self) -> bool {
347        self.get_version().is_http1_0()
348    }
349
350    /// Checks whether the HTTP version is HTTP/1.1.
351    ///
352    /// - Returns: `true` if the version is HTTP/1.1; otherwise, `false`.
353    pub fn version_is_http1_1(&self) -> bool {
354        self.get_version().is_http1_1()
355    }
356
357    /// Checks whether the HTTP version is HTTP/2.
358    ///
359    /// - Returns: `true` if the version is HTTP/2; otherwise, `false`.
360    pub fn version_is_http2(&self) -> bool {
361        self.get_version().is_http2()
362    }
363
364    /// Checks whether the HTTP version is HTTP/3.
365    ///
366    /// - Returns: `true` if the version is HTTP/3; otherwise, `false`.
367    pub fn version_is_http3(&self) -> bool {
368        self.get_version().is_http3()
369    }
370
371    /// Checks whether the HTTP version is unknown.
372    ///
373    /// - Returns: `true` if the version is unknown; otherwise, `false`.
374    pub fn version_is_unknown(&self) -> bool {
375        self.get_version().is_unknown()
376    }
377
378    /// Checks whether the version belongs to the HTTP family.
379    ///
380    /// - Returns: `true` if the version is a valid HTTP version; otherwise, `false`.
381    pub fn version_is_http(&self) -> bool {
382        self.get_version().is_http()
383    }
384
385    /// Checks whether the request method is `GET`.
386    ///
387    /// - Returns: `true` if the method is `GET`; otherwise, `false`.
388    pub fn method_is_get(&self) -> bool {
389        self.get_method().is_get()
390    }
391
392    /// Checks whether the request method is `POST`.
393    ///
394    /// - Returns: `true` if the method is `POST`; otherwise, `false`.
395    pub fn method_is_post(&self) -> bool {
396        self.get_method().is_post()
397    }
398
399    /// Checks whether the request method is `PUT`.
400    ///
401    /// - Returns: `true` if the method is `PUT`; otherwise, `false`.
402    pub fn method_is_put(&self) -> bool {
403        self.get_method().is_put()
404    }
405
406    /// Checks whether the request method is `DELETE`.
407    ///
408    /// - Returns: `true` if the method is `DELETE`; otherwise, `false`.
409    pub fn method_is_delete(&self) -> bool {
410        self.get_method().is_delete()
411    }
412
413    /// Checks whether the request method is `PATCH`.
414    ///
415    /// - Returns: `true` if the method is `PATCH`; otherwise, `false`.
416    pub fn method_is_patch(&self) -> bool {
417        self.get_method().is_patch()
418    }
419
420    /// Checks whether the request method is `HEAD`.
421    ///
422    /// - Returns: `true` if the method is `HEAD`; otherwise, `false`.
423    pub fn method_is_head(&self) -> bool {
424        self.get_method().is_head()
425    }
426
427    /// Checks whether the request method is `OPTIONS`.
428    ///
429    /// - Returns: `true` if the method is `OPTIONS`; otherwise, `false`.
430    pub fn method_is_options(&self) -> bool {
431        self.get_method().is_options()
432    }
433
434    /// Checks whether the request method is `CONNECT`.
435    ///
436    /// - Returns: `true` if the method is `CONNECT`; otherwise, `false`.
437    pub fn method_is_connect(&self) -> bool {
438        self.get_method().is_connect()
439    }
440
441    /// Checks whether the request method is `TRACE`.
442    ///
443    /// - Returns: `true` if the method is `TRACE`; otherwise, `false`.
444    pub fn method_is_trace(&self) -> bool {
445        self.get_method().is_trace()
446    }
447
448    /// Checks whether the request method is `UNKNOWN`.
449    ///
450    /// - Returns: `true` if the method is `UNKNOWN`; otherwise, `false`.
451    pub fn method_is_unknown(&self) -> bool {
452        self.get_method().is_unknown()
453    }
454
455    /// Determines if keep-alive connection should be enabled for this request.
456    ///
457    /// This function checks the Connection header and HTTP version to determine if
458    /// keep-alive should be enabled. The logic is as follows:
459    ///
460    /// 1. If Connection header exists:
461    ///    - Returns true if header value is "keep-alive"
462    ///    - Returns false if header value is "close"
463    /// 2. If no Connection header:
464    ///    - Returns true if HTTP version is 1.1 or higher
465    ///    - Returns false otherwise
466    ///
467    /// # Returns
468    /// - `bool`: true if keep-alive should be enabled, false otherwise
469    pub fn is_enable_keep_alive(&self) -> bool {
470        if let Some(connection_value) = self.get_header(CONNECTION) {
471            let connection_value_lowercase: String = connection_value.to_ascii_lowercase();
472            if connection_value_lowercase == CONNECTION_KEEP_ALIVE {
473                return true;
474            } else if connection_value_lowercase == CONNECTION_CLOSE {
475                return self.upgrade_type_is_websocket();
476            }
477        }
478        self.version_is_http1_1_or_higher() || self.upgrade_type_is_websocket()
479    }
480}