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_xxhash3_64(),
11            headers: hash_map_xxhash3_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    ) -> RequestNewResult {
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        if parts.len() < 3 {
35            return Err(RequestError::InvalidHttpRequest);
36        }
37        let method: RequestMethod = parts[0]
38            .to_string()
39            .parse::<RequestMethod>()
40            .unwrap_or_default();
41        let full_path: RequestPath = parts[1].to_string();
42        let version: RequestVersion = parts[2]
43            .to_string()
44            .parse::<RequestVersion>()
45            .unwrap_or_default();
46        let hash_index: OptionUsize = full_path.find(HASH_SYMBOL);
47        let query_index: OptionUsize = full_path.find(QUERY_SYMBOL);
48        let query_string: String = query_index.map_or(EMPTY_STR.to_owned(), |i| {
49            let temp: String = full_path[i + 1..].to_string();
50            if hash_index.is_none() || hash_index.unwrap() <= i {
51                return temp.into();
52            }
53            let data: String = temp
54                .split(HASH_SYMBOL)
55                .next()
56                .unwrap_or_default()
57                .to_string();
58            data.into()
59        });
60        let querys: RequestQuerys = Self::parse_querys(&query_string);
61        let path: RequestPath = if let Some(i) = query_index.or(hash_index) {
62            full_path[..i].to_string()
63        } else {
64            full_path
65        };
66        let mut headers: RequestHeaders = hash_map_xxhash3_64();
67        let mut host: RequestHost = EMPTY_STR.to_owned();
68        let mut content_length: usize = 0;
69        loop {
70            let mut header_line: String = String::with_capacity(buffer_size);
71            let _ = AsyncBufReadExt::read_line(reader, &mut header_line).await;
72            let header_line: &str = header_line.trim();
73            if header_line.is_empty() {
74                break;
75            }
76            let parts: Vec<&str> = header_line.splitn(2, COLON_SPACE_SYMBOL).collect();
77            if parts.len() != 2 {
78                continue;
79            }
80            let key: String = parts[0].trim().to_ascii_lowercase();
81            let value: String = parts[1].trim().to_string();
82            if key == HOST {
83                host = value.to_string();
84            }
85            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    ) -> RequestNewResult {
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    ///
129    /// # Returns
130    /// - `Ok`: A `Request` object populated with the HTTP request data.
131    /// - `Err`: An `RequestError` if the request is invalid or cannot be read.
132    pub async fn websocket_request_from_stream(
133        stream: &ArcRwLockStream,
134        buffer_size: usize,
135    ) -> RequestNewResult {
136        let mut buf_stream: RwLockWriteGuard<'_, TcpStream> = stream.get_write_lock().await;
137        let mut reader: BufReader<&mut TcpStream> = BufReader::new(&mut buf_stream);
138        Self::websocket_from_reader(&mut reader, buffer_size).await
139    }
140
141    /// Reads a WebSocket request from a TCP stream and constructs a `Request` object.
142    ///
143    /// This function reads data from the provided `BufReader` wrapped around a `TcpStream`.
144    /// It attempts to read up to 1024 bytes into a buffer and constructs a `Request` object
145    /// based on the received data. The request body is set using the received bytes.
146    ///
147    /// # Arguments
148    /// - `reader` - A mutable reference to a `BufReader` wrapping a `TcpStream`.
149    ///   This reader is used to read the incoming WebSocket request data.
150    /// - `buffer_size`: - Request buffer size
151    ///
152    /// # Returns
153    /// - `Ok(Request)` - A `Request` object constructed from the received data.
154    ///   - If no data is read (`Ok(0)`), an empty `Request` object is returned.
155    ///   - If data is successfully read, the request body is set with the received bytes.
156    /// - `Err(RequestError::InvalidWebSocketRequest)` - If an error occurs while reading from the stream.
157    pub async fn websocket_from_reader(
158        reader: &mut BufReader<&mut TcpStream>,
159        buffer_size: usize,
160    ) -> RequestNewResult {
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::with_capacity(buffer_size);
164        loop {
165            let len: usize = match reader.read(&mut temp_buffer).await {
166                Ok(len) => len,
167                Err(_) => return Err(RequestError::InvalidWebSocketRequest),
168            };
169            if len == 0 {
170                break;
171            }
172            dynamic_buffer.extend_from_slice(&temp_buffer[..len]);
173            if let Some((frame, consumed)) =
174                WebSocketFrame::decode_websocket_frame_with_length(&dynamic_buffer)
175            {
176                dynamic_buffer.drain(0..consumed);
177                full_frame.extend_from_slice(frame.get_payload_data());
178                if *frame.get_fin() {
179                    let mut request: Request = Request::default();
180                    request.set_body(full_frame);
181                    return Ok(request);
182                }
183            }
184        }
185        Err(RequestError::InvalidWebSocketRequest)
186    }
187
188    /// Parse querys
189    ///
190    /// # Parameters
191    /// - `query`: &str
192    ///
193    /// # Returns
194    /// - RequestQuerys
195    fn parse_querys(query: &str) -> RequestQuerys {
196        let mut query_map: RequestQuerys = hash_map_xxhash3_64();
197        for pair in query.split(AND) {
198            let mut parts: SplitN<'_, &str> = pair.splitn(2, EQUAL);
199            let key: String = parts.next().unwrap_or_default().to_string();
200            let value: String = parts.next().unwrap_or_default().to_string();
201            if !key.is_empty() {
202                query_map.insert(key, value);
203            }
204        }
205        query_map
206    }
207
208    /// Retrieves the value of a query parameter by its key.
209    ///
210    /// # Parameters
211    /// - `key`: The query parameter's key, which can be of any type that implements `Into<RequestQuerysKey>`.
212    ///
213    /// # Returns
214    /// - `OptionRequestQuerysValue`: Returns `Some(value)` if the key exists in the query parameters,
215    ///   or `None` if the key does not exist.
216    pub fn get_query<K>(&self, key: K) -> OptionRequestQuerysValue
217    where
218        K: Into<RequestQuerysKey>,
219    {
220        self.querys
221            .get(&key.into())
222            .and_then(|data| Some(data.clone()))
223    }
224
225    /// Retrieves the value of a request header by its key.
226    ///
227    /// # Parameters
228    /// - `key`: The header's key, which can be of any type that implements `Into<RequestHeadersKey>`.
229    ///
230    /// # Returns
231    /// - `OptionRequestHeadersValue`: Returns `Some(value)` if the key exists in the request headers,
232    ///   or `None` if the key does not exist.
233    pub fn get_header<K>(&self, key: K) -> OptionRequestHeadersValue
234    where
235        K: Into<RequestHeadersKey>,
236    {
237        self.headers
238            .get(&key.into())
239            .and_then(|data| Some(data.clone()))
240    }
241
242    /// Adds a header to the request.
243    ///
244    /// This function inserts a key-value pair into the request headers.
245    /// The key and value are converted into `String`, allowing for efficient handling of both owned and borrowed string data.
246    ///
247    /// # Parameters
248    /// - `key`: The header key, which will be converted into a `String`.
249    /// - `value`: The value of the header, which will be converted into a `String`.
250    ///
251    /// # Returns
252    /// - Returns a mutable reference to the current instance (`&mut Self`), allowing for method chaining.
253    pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
254    where
255        K: Into<String>,
256        V: Into<String>,
257    {
258        self.headers.insert(key.into(), value.into());
259        self
260    }
261
262    /// Set the body of the response.
263    ///
264    /// This method allows you to set the body of the response by converting the provided
265    /// value into a `RequestBody` type. The `body` is updated with the converted value,
266    /// and the method returns a mutable reference to the current instance for method chaining.
267    ///
268    /// # Parameters
269    /// - `body`: The body of the response to be set. It can be any type that can be converted
270    ///   into a `RequestBody` using the `Into` trait.
271    ///
272    /// # Return Value
273    /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
274    /// Set the body of the response.
275    ///
276    /// This method allows you to set the body of the response by converting the provided
277    /// value into a `RequestBody` type. The `body` is updated with the converted value,
278    /// and the method returns a mutable reference to the current instance for method chaining.
279    ///
280    /// # Parameters
281    /// - `body`: The body of the response to be set. It can be any type that can be converted
282    ///   into a `RequestBody` using the `Into` trait.
283    ///
284    /// # Return Value
285    /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
286    pub fn set_body<T: Into<RequestBody>>(&mut self, body: T) -> &mut Self {
287        self.body = body.into();
288        self
289    }
290
291    /// Set the HTTP method of the request.
292    ///
293    /// This method allows you to set the HTTP method (e.g., GET, POST) of the request
294    /// by converting the provided value into a `RequestMethod` type. The `method` is updated
295    /// with the converted value, and the method returns a mutable reference to the current
296    /// instance for method chaining.
297    ///
298    /// # Parameters
299    /// - `method`: The HTTP method to be set for the request. It can be any type that can
300    ///   be converted into a `RequestMethod` using the `Into` trait.
301    ///
302    /// # Return Value
303    /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
304    pub fn set_method<T: Into<RequestMethod>>(&mut self, method: T) -> &mut Self {
305        self.method = method.into();
306        self
307    }
308
309    /// Set the host of the request.
310    ///
311    /// This method allows you to set the host (e.g., www.example.com) for the request
312    /// by converting the provided value into a `RequestHost` type. The `host` is updated
313    /// with the converted value, and the method returns a mutable reference to the current
314    /// instance for method chaining.
315    ///
316    /// # Parameters
317    /// - `host`: The host to be set for the request. It can be any type that can be converted
318    ///   into a `RequestHost` using the `Into` trait.
319    ///
320    /// # Return Value
321    /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
322    pub fn set_host<T: Into<RequestHost>>(&mut self, host: T) -> &mut Self {
323        self.host = host.into();
324        self
325    }
326
327    /// Set the path of the request.
328    ///
329    /// This method allows you to set the path (e.g., /api/v1/resource) for the request
330    /// by converting the provided value into a `RequestPath` type. The `path` is updated
331    /// with the converted value, and the method returns a mutable reference to the current
332    /// instance for method chaining.
333    ///
334    /// # Parameters
335    /// - `path`: The path to be set for the request. It can be any type that can be converted
336    ///   into a `RequestPath` using the `Into` trait.
337    ///
338    /// # Return Value
339    /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
340    pub fn set_path<T: Into<RequestPath>>(&mut self, path: T) -> &mut Self {
341        self.path = path.into();
342        self
343    }
344
345    /// Sets a query parameter for the request.
346    ///
347    /// # Parameters
348    /// - `key`: The query parameter's key, which can be of any type that implements `Into<RequestQuerysKey>`.
349    /// - `value`: The query parameter's value, which can be of any type that implements `Into<RequestQuerysValue>`.
350    ///
351    /// # Returns
352    /// - Returns a mutable reference to the current instance (`Self`), allowing for method chaining.
353    pub fn set_query<K: Into<RequestQuerysKey>, V: Into<RequestQuerysValue>>(
354        &mut self,
355        key: K,
356        value: V,
357    ) -> &mut Self {
358        self.querys.insert(key.into(), value.into());
359        self
360    }
361
362    /// Converts the request to a formatted string representation.
363    ///
364    /// - Returns: A `String` containing formatted request details.
365    pub fn get_string(&self) -> String {
366        let body: &Vec<u8> = self.get_body();
367        format!(
368            "[Request] => [Method]: {}; [Host]: {}; [Version]: {}; [Path]: {}; [Querys]: {:?}; [Headers]: {:?}; [Body]: {};",
369            self.get_method(),
370            self.get_host(),
371            self.get_version(),
372            self.get_path(),
373            self.get_querys(),
374            self.get_headers(),
375            body_to_string(body),
376        )
377    }
378
379    /// Retrieves the upgrade type from the request headers.
380    ///
381    /// - Returns: The `UpgradeType` extracted from the `UPGRADE` header.
382    ///            If the header is missing or invalid, returns the default `UpgradeType`.
383    pub fn get_upgrade_type(&self) -> UpgradeType {
384        let upgrade_type: UpgradeType = self
385            .get_header(UPGRADE)
386            .and_then(|data| data.parse::<UpgradeType>().ok())
387            .unwrap_or_default();
388        upgrade_type
389    }
390}