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: String::new(),
9 host: String::new(),
10 path: String::new(),
11 query: HashMap::new(),
12 headers: HashMap::new(),
13 body: Vec::new(),
14 }
15 }
16}
17
18impl Request {
19 /// Creates a new `Request` object from a TCP stream.
20 ///
21 /// # Parameters
22 /// - `reader`: A mut reference to a `&mut BufReader<&mut TcpStream>`
23 ///
24 /// # Returns
25 /// - `Ok`: A `Request` object populated with the HTTP request data.
26 /// - `Err`: An `Error` if the request is invalid or cannot be read.
27 #[inline]
28 pub async fn from_reader(reader: &mut BufReader<&mut TcpStream>) -> RequestNewResult {
29 let mut request_line: String = String::new();
30 let _ = AsyncBufReadExt::read_line(reader, &mut request_line).await;
31 let parts: Vec<&str> = request_line.split_whitespace().collect();
32 if parts.len() < 3 {
33 return Err(Error::InvalidHttpRequest);
34 }
35 let method: RequestMethod = parts[0].to_string();
36 let full_path: String = parts[1].to_string();
37 let hash_index: Option<usize> = full_path.find(HASH_SYMBOL);
38 let query_index: Option<usize> = full_path.find(QUERY_SYMBOL);
39 let query_string: String = query_index.map_or(EMPTY_STR.to_owned(), |i| {
40 let temp: String = full_path[i + 1..].to_string();
41 if hash_index.is_none() || hash_index.unwrap() <= i {
42 return temp.into();
43 }
44 let data: String = temp
45 .split(HASH_SYMBOL)
46 .next()
47 .unwrap_or_default()
48 .to_string();
49 data.into()
50 });
51 let query: RequestQuery = Self::parse_query(&query_string);
52 let path: RequestPath = if let Some(i) = query_index.or(hash_index) {
53 full_path[..i].to_string()
54 } else {
55 full_path
56 };
57 let mut headers: RequestHeaders = HashMap::new();
58 let mut host: RequestHost = EMPTY_STR.to_owned();
59 let mut content_length: usize = 0;
60 loop {
61 let mut header_line: String = String::new();
62 let _ = AsyncBufReadExt::read_line(reader, &mut header_line).await;
63 let header_line: &str = header_line.trim();
64 if header_line.is_empty() {
65 break;
66 }
67 let parts: Vec<&str> = header_line.splitn(2, COLON_SPACE_SYMBOL).collect();
68 if parts.len() != 2 {
69 continue;
70 }
71 let key: String = parts[0].trim().to_string();
72 let value: String = parts[1].trim().to_string();
73 if key.eq_ignore_ascii_case(HOST) {
74 host = value.to_string();
75 }
76 if key.eq_ignore_ascii_case(CONTENT_LENGTH) {
77 content_length = value.parse().unwrap_or(0);
78 }
79 headers.insert(key, value);
80 }
81 let mut body: RequestBody = Vec::new();
82 if content_length > 0 {
83 body.resize(content_length, 0);
84 let _ = AsyncReadExt::read_exact(reader, &mut body);
85 }
86 Ok(Request {
87 method,
88 host,
89 path,
90 query,
91 headers,
92 body,
93 })
94 }
95
96 /// Creates a new `Request` object from a TCP stream.
97 ///
98 /// # Parameters
99 /// - `stream`: A reference to a `&ArcRwLockStream` representing the incoming connection.
100 ///
101 /// # Returns
102 /// - `Ok`: A `Request` object populated with the HTTP request data.
103 /// - `Err`: An `Error` if the request is invalid or cannot be read.
104 #[inline]
105 pub async fn from_stream(stream: &ArcRwLockStream) -> RequestNewResult {
106 let mut buf_stream: RwLockWriteGuard<'_, TcpStream> = stream.write().await;
107 let mut reader: BufReader<&mut TcpStream> = BufReader::new(&mut buf_stream);
108 Self::from_reader(&mut reader).await
109 }
110
111 /// Parse query
112 ///
113 /// # Parameters
114 /// - `query`: &str
115 ///
116 /// # Returns
117 /// - RequestQuery
118 #[inline]
119 fn parse_query(query: &str) -> RequestQuery {
120 let mut query_map: RequestQuery = HashMap::new();
121 for pair in query.split(AND) {
122 let mut parts: SplitN<'_, &str> = pair.splitn(2, EQUAL);
123 let key: String = parts.next().unwrap_or_default().to_string();
124 let value: String = parts.next().unwrap_or_default().to_string();
125 if !key.is_empty() {
126 query_map.insert(key, value);
127 }
128 }
129 query_map
130 }
131
132 /// Adds a header to the request.
133 ///
134 /// This function inserts a key-value pair into the request headers.
135 /// The key and value are converted into `String`, allowing for efficient handling of both owned and borrowed string data.
136 ///
137 /// # Parameters
138 /// - `key`: The header key, which will be converted into a `String`.
139 /// - `value`: The value of the header, which will be converted into a `String`.
140 ///
141 /// # Returns
142 /// - Returns a mutable reference to the current instance (`&mut Self`), allowing for method chaining.
143 #[inline]
144 pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
145 where
146 K: Into<String>,
147 V: Into<String>,
148 {
149 self.headers.insert(key.into(), value.into());
150 self
151 }
152
153 /// Set the body of the response.
154 ///
155 /// This method allows you to set the body of the response by converting the provided
156 /// value into a `RequestBody` type. The `body` is updated with the converted value,
157 /// and the method returns a mutable reference to the current instance for method chaining.
158 ///
159 /// # Parameters
160 /// - `body`: The body of the response to be set. It can be any type that can be converted
161 /// into a `RequestBody` using the `Into` trait.
162 ///
163 /// # Return Value
164 /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
165 /// Set the body of the response.
166 ///
167 /// This method allows you to set the body of the response by converting the provided
168 /// value into a `RequestBody` type. The `body` is updated with the converted value,
169 /// and the method returns a mutable reference to the current instance for method chaining.
170 ///
171 /// # Parameters
172 /// - `body`: The body of the response to be set. It can be any type that can be converted
173 /// into a `RequestBody` using the `Into` trait.
174 ///
175 /// # Return Value
176 /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
177 #[inline]
178 pub fn set_body<T: Into<RequestBody>>(&mut self, body: T) -> &mut Self {
179 self.body = body.into();
180 self
181 }
182
183 /// Set the HTTP method of the request.
184 ///
185 /// This method allows you to set the HTTP method (e.g., GET, POST) of the request
186 /// by converting the provided value into a `RequestMethod` type. The `method` is updated
187 /// with the converted value, and the method returns a mutable reference to the current
188 /// instance for method chaining.
189 ///
190 /// # Parameters
191 /// - `method`: The HTTP method to be set for the request. It can be any type that can
192 /// be converted into a `RequestMethod` using the `Into` trait.
193 ///
194 /// # Return Value
195 /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
196 #[inline]
197 pub fn set_method<T: Into<RequestMethod>>(&mut self, method: T) -> &mut Self {
198 self.method = method.into();
199 self
200 }
201
202 /// Set the host of the request.
203 ///
204 /// This method allows you to set the host (e.g., www.example.com) for the request
205 /// by converting the provided value into a `RequestHost` type. The `host` is updated
206 /// with the converted value, and the method returns a mutable reference to the current
207 /// instance for method chaining.
208 ///
209 /// # Parameters
210 /// - `host`: The host to be set for the request. It can be any type that can be converted
211 /// into a `RequestHost` using the `Into` trait.
212 ///
213 /// # Return Value
214 /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
215 #[inline]
216 pub fn set_host<T: Into<RequestHost>>(&mut self, host: T) -> &mut Self {
217 self.host = host.into();
218 self
219 }
220
221 /// Set the path of the request.
222 ///
223 /// This method allows you to set the path (e.g., /api/v1/resource) for the request
224 /// by converting the provided value into a `RequestPath` type. The `path` is updated
225 /// with the converted value, and the method returns a mutable reference to the current
226 /// instance for method chaining.
227 ///
228 /// # Parameters
229 /// - `path`: The path to be set for the request. It can be any type that can be converted
230 /// into a `RequestPath` using the `Into` trait.
231 ///
232 /// # Return Value
233 /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
234 #[inline]
235 pub fn set_path<T: Into<RequestPath>>(&mut self, path: T) -> &mut Self {
236 self.path = path.into();
237 self
238 }
239
240 /// Set the query string of the request.
241 ///
242 /// This method allows you to set the query string (e.g., ?key=value) for the request
243 /// by converting the provided value into a `RequestQuery` type. The `query` is updated
244 /// with the converted value, and the method returns a mutable reference to the current
245 /// instance for method chaining.
246 ///
247 /// # Parameters
248 /// - `query`: The query string to be set for the request. It can be any type that can
249 /// be converted into a `RequestQuery` using the `Into` trait.
250 ///
251 /// # Return Value
252 /// - Returns a mutable reference to the current instance of the struct, enabling method chaining.
253 #[inline]
254 pub fn set_query<T: Into<RequestQuery>>(&mut self, query: T) -> &mut Self {
255 self.query = query.into();
256 self
257 }
258}