http_type/request/
impl.rs

1use super::error::Error;
2use crate::*;
3
4impl Default for Request {
5    #[inline]
6    fn default() -> Self {
7        Self {
8            method: Methods::default(),
9            host: String::new(),
10            version: HttpVersion::default(),
11            path: String::new(),
12            querys: HashMap::new(),
13            headers: HashMap::new(),
14            body: Vec::new(),
15            upgrade_type: UpgradeType::default(),
16        }
17    }
18}
19
20impl Request {
21    /// Creates a new `Request` object from a TCP stream.
22    ///
23    /// # Parameters
24    /// - `reader`: A mut reference to a `&mut BufReader<&mut TcpStream>`
25    ///
26    /// # Returns
27    /// - `Ok`: A `Request` object populated with the HTTP request data.
28    /// - `Err`: An `Error` if the request is invalid or cannot be read.
29    #[inline]
30    pub async fn http_from_reader(reader: &mut BufReader<&mut TcpStream>) -> RequestNewResult {
31        let mut request_line: String = String::new();
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(Error::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: Option<usize> = full_path.find(HASH_SYMBOL);
47        let query_index: Option<usize> = 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 = HashMap::new();
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::new();
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_string();
81            let value: String = parts[1].trim().to_string();
82            if key.eq_ignore_ascii_case(HOST) {
83                host = value.to_string();
84            }
85            if key.eq_ignore_ascii_case(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        let upgrade_type: UpgradeType = headers
95            .get(UPGRADE)
96            .and_then(|data| data.parse::<UpgradeType>().ok())
97            .unwrap_or_default();
98        Ok(Request {
99            method,
100            host,
101            version,
102            path,
103            querys,
104            headers,
105            body,
106            upgrade_type,
107        })
108    }
109
110    /// Creates a new `Request` object from a TCP stream.
111    ///
112    /// # Parameters
113    /// - `stream`: A reference to a `&ArcRwLockStream` representing the incoming connection.
114    ///
115    /// # Returns
116    /// - `Ok`: A `Request` object populated with the HTTP request data.
117    /// - `Err`: An `Error` if the request is invalid or cannot be read.
118    #[inline]
119    pub async fn http_request_from_stream(stream: &ArcRwLockStream) -> RequestNewResult {
120        let mut buf_stream: RwLockWriteGuard<'_, TcpStream> = stream.get_write_lock().await;
121        let mut reader: BufReader<&mut TcpStream> = BufReader::new(&mut buf_stream);
122        Self::http_from_reader(&mut reader).await
123    }
124
125    /// Creates a new `Request` object from a TCP stream.
126    ///
127    /// # Parameters
128    /// - `stream`: A reference to a `&ArcRwLockStream` representing the incoming connection.
129    /// - `buffer_size`: Request buffer size
130    ///
131    /// # Returns
132    /// - `Ok`: A `Request` object populated with the HTTP request data.
133    /// - `Err`: An `Error` if the request is invalid or cannot be read.
134    #[inline]
135    pub async fn websocket_request_from_stream(
136        stream: &ArcRwLockStream,
137        buffer_size: usize,
138    ) -> RequestNewResult {
139        let mut buf_stream: RwLockWriteGuard<'_, TcpStream> = stream.get_write_lock().await;
140        let mut reader: BufReader<&mut TcpStream> = BufReader::new(&mut buf_stream);
141        Self::websocket_from_reader(&mut reader, buffer_size).await
142    }
143
144    /// Reads a WebSocket request from a TCP stream and constructs a `Request` object.
145    ///
146    /// This function reads data from the provided `BufReader` wrapped around a `TcpStream`.
147    /// It attempts to read up to 1024 bytes into a buffer and constructs a `Request` object
148    /// based on the received data. The request body is set using the received bytes.
149    ///
150    /// # Arguments
151    /// - `reader` - A mutable reference to a `BufReader` wrapping a `TcpStream`.
152    ///   This reader is used to read the incoming WebSocket request data.
153    /// - `buffer_size`: - Request buffer size
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    #[inline]
161    pub async fn websocket_from_reader(
162        reader: &mut BufReader<&mut TcpStream>,
163        buffer_size: usize,
164    ) -> RequestNewResult {
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(_) => return Err(RequestError::InvalidWebSocketRequest),
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::default();
184                    request.set_body(full_frame);
185                    return Ok(request);
186                }
187            }
188        }
189        Err(RequestError::InvalidWebSocketRequest)
190    }
191
192    /// Parse querys
193    ///
194    /// # Parameters
195    /// - `query`: &str
196    ///
197    /// # Returns
198    /// - RequestQuerys
199    #[inline]
200    fn parse_querys(query: &str) -> RequestQuerys {
201        let mut query_map: RequestQuerys = HashMap::new();
202        for pair in query.split(AND) {
203            let mut parts: SplitN<'_, &str> = pair.splitn(2, EQUAL);
204            let key: String = parts.next().unwrap_or_default().to_string();
205            let value: String = parts.next().unwrap_or_default().to_string();
206            if !key.is_empty() {
207                query_map.insert(key, value);
208            }
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    /// - `Option<RequestQuerysValue>`: Returns `Some(value)` if the key exists in the query parameters,
220    ///   or `None` if the key does not exist.
221    #[inline]
222    pub fn get_query<K>(&self, key: K) -> Option<RequestQuerysValue>
223    where
224        K: Into<RequestQuerysKey>,
225    {
226        self.querys
227            .get(&key.into())
228            .and_then(|data| Some(data.clone()))
229    }
230
231    /// Retrieves the value of a request header by its key.
232    ///
233    /// # Parameters
234    /// - `key`: The header's key, which can be of any type that implements `Into<RequestHeadersKey>`.
235    ///
236    /// # Returns
237    /// - `Option<RequestHeadersValue>`: Returns `Some(value)` if the key exists in the request headers,
238    ///   or `None` if the key does not exist.
239    #[inline]
240    pub fn get_header<K>(&self, key: K) -> Option<RequestHeadersValue>
241    where
242        K: Into<RequestHeadersKey>,
243    {
244        self.headers
245            .get(&key.into())
246            .and_then(|data| Some(data.clone()))
247    }
248
249    /// Adds a header to the request.
250    ///
251    /// This function inserts a key-value pair into the request headers.
252    /// The key and value are converted into `String`, allowing for efficient handling of both owned and borrowed string data.
253    ///
254    /// # Parameters
255    /// - `key`: The header key, which will be converted into a `String`.
256    /// - `value`: The value of the header, which will be converted into a `String`.
257    ///
258    /// # Returns
259    /// - Returns a mutable reference to the current instance (`&mut Self`), allowing for method chaining.
260    #[inline]
261    pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
262    where
263        K: Into<String>,
264        V: Into<String>,
265    {
266        self.headers.insert(key.into(), value.into());
267        self
268    }
269
270    /// Set the body of the response.
271    ///
272    /// This method allows you to set the body of the response by converting the provided
273    /// value into a `RequestBody` type. The `body` is updated with the converted value,
274    /// and the method returns a mutable reference to the current instance for method chaining.
275    ///
276    /// # Parameters
277    /// - `body`: The body of the response to be set. It can be any type that can be converted
278    ///   into a `RequestBody` using the `Into` trait.
279    ///
280    /// # Return Value
281    /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
282    /// Set the body of the response.
283    ///
284    /// This method allows you to set the body of the response by converting the provided
285    /// value into a `RequestBody` type. The `body` is updated with the converted value,
286    /// and the method returns a mutable reference to the current instance for method chaining.
287    ///
288    /// # Parameters
289    /// - `body`: The body of the response to be set. It can be any type that can be converted
290    ///   into a `RequestBody` using the `Into` trait.
291    ///
292    /// # Return Value
293    /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
294    #[inline]
295    pub fn set_body<T: Into<RequestBody>>(&mut self, body: T) -> &mut Self {
296        self.body = body.into();
297        self
298    }
299
300    /// Set the HTTP method of the request.
301    ///
302    /// This method allows you to set the HTTP method (e.g., GET, POST) of the request
303    /// by converting the provided value into a `RequestMethod` type. The `method` is updated
304    /// with the converted value, and the method returns a mutable reference to the current
305    /// instance for method chaining.
306    ///
307    /// # Parameters
308    /// - `method`: The HTTP method to be set for the request. It can be any type that can
309    ///   be converted into a `RequestMethod` using the `Into` trait.
310    ///
311    /// # Return Value
312    /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
313    #[inline]
314    pub fn set_method<T: Into<RequestMethod>>(&mut self, method: T) -> &mut Self {
315        self.method = method.into();
316        self
317    }
318
319    /// Set the host of the request.
320    ///
321    /// This method allows you to set the host (e.g., www.example.com) for the request
322    /// by converting the provided value into a `RequestHost` type. The `host` is updated
323    /// with the converted value, and the method returns a mutable reference to the current
324    /// instance for method chaining.
325    ///
326    /// # Parameters
327    /// - `host`: The host to be set for the request. It can be any type that can be converted
328    ///   into a `RequestHost` using the `Into` trait.
329    ///
330    /// # Return Value
331    /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
332    #[inline]
333    pub fn set_host<T: Into<RequestHost>>(&mut self, host: T) -> &mut Self {
334        self.host = host.into();
335        self
336    }
337
338    /// Set the path of the request.
339    ///
340    /// This method allows you to set the path (e.g., /api/v1/resource) for the request
341    /// by converting the provided value into a `RequestPath` type. The `path` is updated
342    /// with the converted value, and the method returns a mutable reference to the current
343    /// instance for method chaining.
344    ///
345    /// # Parameters
346    /// - `path`: The path to be set for the request. It can be any type that can be converted
347    ///   into a `RequestPath` using the `Into` trait.
348    ///
349    /// # Return Value
350    /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
351    #[inline]
352    pub fn set_path<T: Into<RequestPath>>(&mut self, path: T) -> &mut Self {
353        self.path = path.into();
354        self
355    }
356
357    /// Sets a query parameter for the request.
358    ///
359    /// # Parameters
360    /// - `key`: The query parameter's key, which can be of any type that implements `Into<RequestQuerysKey>`.
361    /// - `value`: The query parameter's value, which can be of any type that implements `Into<RequestQuerysValue>`.
362    ///
363    /// # Returns
364    /// - Returns a mutable reference to the current instance (`Self`), allowing for method chaining.
365    #[inline]
366    pub fn set_query<K: Into<RequestQuerysKey>, V: Into<RequestQuerysValue>>(
367        &mut self,
368        key: K,
369        value: V,
370    ) -> &mut Self {
371        self.querys.insert(key.into(), value.into());
372        self
373    }
374}