http_request/request/request_builder/impl.rs
1use crate::*;
2
3impl Default for RequestBuilder {
4 fn default() -> Self {
5 Self {
6 http_request: HttpRequest::default(),
7 builder: HttpRequest::default(),
8 }
9 }
10}
11
12impl RequestBuilder {
13 /// Creates a new RequestBuilder instance.
14 ///
15 /// # Returns
16 ///
17 /// - `RequestBuilder` - A new builder instance with default values.
18 pub fn new() -> Self {
19 Self::default()
20 }
21
22 /// Sets the HTTP method to POST and the request URL.
23 ///
24 /// # Arguments
25 ///
26 /// - `str` - The request URL.
27 ///
28 /// # Returns
29 ///
30 /// - `&mut RequestBuilder` - The builder for method chaining.
31 pub fn post(&mut self, url: &str) -> &mut Self {
32 self.http_request.methods = Arc::new(Method::POST);
33 self.url(url);
34 self
35 }
36
37 /// Sets the HTTP method to GET and the request URL.
38 ///
39 /// # Arguments
40 ///
41 /// - `str` - The request URL.
42 ///
43 /// # Returns
44 ///
45 /// - `&mut RequestBuilder` - The builder for method chaining.
46 pub fn get(&mut self, url: &str) -> &mut Self {
47 self.http_request.methods = Arc::new(Method::GET);
48 self.url(url);
49 self
50 }
51
52 /// Sets the request URL.
53 ///
54 /// # Arguments
55 ///
56 /// - `&str` - The request URL.
57 ///
58 /// # Returns
59 ///
60 /// - `&mut RequestBuilder` - The builder for method chaining.
61 fn url(&mut self, url: &str) -> &mut Self {
62 self.http_request.url = Arc::new(url.to_owned());
63 self
64 }
65
66 /// Forces HTTP/1.1 protocol version.
67 ///
68 /// # Returns
69 ///
70 /// - `&mut RequestBuilder` - The builder for method chaining.
71 pub fn http1_1_only(&mut self) -> &mut Self {
72 if let Ok(mut config) = self.http_request.config.write() {
73 config.http_version = HttpVersion::HTTP1_1;
74 }
75 self
76 }
77
78 /// Forces HTTP/2 protocol version.
79 ///
80 /// # Returns
81 ///
82 /// - `&mut RequestBuilder` - The builder for method chaining.
83 pub fn http2_only(&mut self) -> &mut Self {
84 if let Ok(mut config) = self.http_request.config.write() {
85 config.http_version = HttpVersion::HTTP2;
86 }
87 self
88 }
89
90 /// Sets request headers.
91 ///
92 /// # Arguments
93 ///
94 /// - `HashMapXxHash3_64<K, V>` - The headers to set.
95 ///
96 /// # Returns
97 ///
98 /// - `&mut RequestBuilder` - The builder for method chaining.
99 pub fn headers<K, V>(&mut self, header: HashMapXxHash3_64<K, V>) -> &mut Self
100 where
101 K: ToString,
102 V: ToString,
103 {
104 if let Some(tmp_header) = Arc::get_mut(&mut self.http_request.header) {
105 for (key, value) in header {
106 let key_str: String = key.to_string();
107 let value_str: String = value.to_string();
108 let mut found_existing: bool = false;
109 let mut existing_key: Option<String> = None;
110 for existing_key_ref in tmp_header.keys() {
111 if existing_key_ref.eq_ignore_ascii_case(&key_str) {
112 existing_key = Some(existing_key_ref.clone());
113 found_existing = true;
114 break;
115 }
116 }
117 if found_existing && let Some(existing_key) = existing_key {
118 tmp_header.remove(&existing_key);
119 }
120 let mut value_deque: VecDeque<String> = VecDeque::new();
121 value_deque.push_front(value_str);
122 tmp_header.insert(key_str, value_deque);
123 }
124 }
125 self
126 }
127
128 /// Sets JSON request body.
129 ///
130 /// # Arguments
131 ///
132 /// - `JsonValue` - The JSON body data.
133 ///
134 /// # Returns
135 ///
136 /// - `&mut RequestBuilder` - The builder for method chaining.
137 pub fn json(&mut self, body: JsonValue) -> &mut Self {
138 if let JsonValue::Object(map) = body {
139 let mut res_body: HashMapXxHash3_64<String, JsonValue> = hash_map_xx_hash3_64();
140 for (k, v) in map.iter() {
141 res_body.insert(k.to_string(), v.clone());
142 }
143 self.http_request.body = Arc::new(Body::Json(res_body));
144 }
145 self
146 }
147
148 /// Sets plain text request body.
149 ///
150 /// # Arguments
151 ///
152 /// - `T` - The text body data (must implement ToString).
153 ///
154 /// # Returns
155 ///
156 /// - `&mut RequestBuilder` - The builder for method chaining.
157 pub fn text<T: ToString>(&mut self, body: T) -> &mut Self {
158 self.http_request.body = Arc::new(Body::Text(body.to_string()));
159 self
160 }
161
162 /// Sets binary request body.
163 ///
164 /// # Arguments
165 ///
166 /// - `T` - The binary body data (must implement Into<Vec<u8>>).
167 ///
168 /// # Returns
169 ///
170 /// - `&mut RequestBuilder` - The builder for method chaining.
171 pub fn body<T: Into<Vec<u8>>>(&mut self, body: T) -> &mut Self {
172 self.http_request.body = Arc::new(Body::Binary(body.into()));
173 self
174 }
175
176 /// Sets the timeout value for the current connection.
177 ///
178 /// This method sets the timeout duration for the connection, which is used to determine
179 /// how long the system should wait for a response before considering the connection attempt
180 /// as failed. The timeout value is stored in an `Arc` to allow it to be shared safely across
181 /// multiple threads if needed.
182 ///
183 /// # Arguments
184 ///
185 /// - `u64` - The timeout duration in seconds. This value will be used to configure the
186 /// connection timeout.
187 ///
188 /// # Returns
189 ///
190 /// - `&mut RequestBuilder` - The builder for method chaining.
191 pub fn timeout(&mut self, timeout: u64) -> &mut Self {
192 if let Ok(mut config) = self.http_request.config.write() {
193 config.timeout = timeout;
194 }
195 self
196 }
197
198 /// Enables HTTP redirection for the request.
199 ///
200 /// This method sets the `redirect` property of the `http_request` to `true`.
201 ///
202 /// # Returns
203 ///
204 /// - `&mut RequestBuilder` - The builder for method chaining.
205 pub fn redirect(&mut self) -> &mut Self {
206 if let Ok(mut config) = self.http_request.config.write() {
207 config.redirect = true;
208 }
209 self
210 }
211
212 /// Unenables HTTP redirection for the request.
213 ///
214 /// This method sets the `redirect` property of the `http_request` to `false`.
215 ///
216 /// # Returns
217 ///
218 /// - `&mut RequestBuilder` - The builder for method chaining.
219 pub fn unredirect(&mut self) -> &mut Self {
220 if let Ok(mut config) = self.http_request.config.write() {
221 config.redirect = false;
222 };
223 self
224 }
225
226 /// Sets the maximum number of allowed redirections for the HTTP request.
227 ///
228 /// This method updates the `max_redirect_times` field in the configuration and returns a mutable
229 /// reference to `self` to enable method chaining.
230 ///
231 /// # Arguments
232 ///
233 /// - `usize` - The maximum number of redirections allowed. A value of `0` disables redirection.
234 ///
235 /// # Returns
236 ///
237 /// - `&mut RequestBuilder` - A mutable reference to the current instance for method chaining.
238 ///
239 /// # Notes
240 ///
241 /// Ensure that the value provided to `num` is within a valid range. Excessively high values
242 /// may lead to performance issues or unintended behavior.
243 pub fn max_redirect_times(&mut self, num: usize) -> &mut Self {
244 if let Ok(mut config) = self.http_request.config.write() {
245 config.max_redirect_times = num;
246 }
247 self
248 }
249
250 /// Sets the buffer size for the HTTP request configuration.
251 ///
252 /// This method allows you to set the size of the buffer used for reading
253 /// the HTTP response. It modifies the `buffer` field of the HTTP request's
254 /// configuration, which will be used when processing the response data.
255 ///
256 /// # Arguments
257 ///
258 /// - `usize` - The size of the buffer to be used, in bytes.
259 ///
260 /// # Returns
261 ///
262 /// - `&mut RequestBuilder` - Returns a mutable reference to `self`, allowing for method chaining.
263 pub fn buffer(&mut self, buffer: usize) -> &mut Self {
264 if let Ok(mut config) = self.http_request.config.write() {
265 config.buffer = buffer;
266 }
267 self
268 }
269
270 /// Enables automatic response decoding.
271 ///
272 /// When enabled, the response body will be automatically decompressed if it is encoded
273 /// using a supported compression format.
274 ///
275 /// # Returns
276 ///
277 /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
278 pub fn decode(&mut self) -> &mut Self {
279 if let Ok(mut config) = self.http_request.config.write() {
280 config.decode = true;
281 }
282 self
283 }
284
285 /// Disables automatic response decoding.
286 ///
287 /// When disabled, the response body will not be automatically decompressed,
288 /// and the raw encoded data will be returned as-is.
289 ///
290 /// # Returns
291 ///
292 /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
293 pub fn undecode(&mut self) -> &mut Self {
294 if let Ok(mut config) = self.http_request.config.write() {
295 config.decode = false;
296 }
297 self
298 }
299
300 /// Sets an HTTP proxy for the request.
301 ///
302 /// This method configures the request to use an HTTP proxy server.
303 ///
304 /// # Arguments
305 ///
306 /// - `str` - The hostname or IP address of the proxy server.
307 /// - `u16` - The port number of the proxy server.
308 ///
309 /// # Returns
310 ///
311 /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
312 pub fn http_proxy(&mut self, host: &str, port: u16) -> &mut Self {
313 if let Ok(mut config) = self.http_request.config.write() {
314 config.proxy = Some(ProxyConfig {
315 proxy_type: ProxyType::Http,
316 host: host.to_string(),
317 port,
318 username: None,
319 password: None,
320 });
321 }
322 self
323 }
324
325 /// Sets an HTTPS proxy for the request.
326 ///
327 /// This method configures the request to use an HTTPS proxy server.
328 ///
329 /// # Arguments
330 ///
331 /// - `str` - The hostname or IP address of the proxy server.
332 /// - `u16` - The port number of the proxy server.
333 ///
334 /// # Returns
335 ///
336 /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
337 pub fn https_proxy(&mut self, host: &str, port: u16) -> &mut Self {
338 if let Ok(mut config) = self.http_request.config.write() {
339 config.proxy = Some(ProxyConfig {
340 proxy_type: ProxyType::Https,
341 host: host.to_string(),
342 port,
343 username: None,
344 password: None,
345 });
346 }
347 self
348 }
349
350 /// Sets a SOCKS5 proxy for the request.
351 ///
352 /// This method configures the request to use a SOCKS5 proxy server.
353 ///
354 /// # Arguments
355 ///
356 /// - `str` - The hostname or IP address of the proxy server.
357 /// - `u16` - The port number of the proxy server.
358 ///
359 /// # Returns
360 ///
361 /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
362 pub fn socks5_proxy(&mut self, host: &str, port: u16) -> &mut Self {
363 if let Ok(mut config) = self.http_request.config.write() {
364 config.proxy = Some(ProxyConfig {
365 proxy_type: ProxyType::Socks5,
366 host: host.to_string(),
367 port,
368 username: None,
369 password: None,
370 });
371 }
372 self
373 }
374
375 /// Sets an HTTP proxy with authentication for the request.
376 ///
377 /// This method configures the request to use an HTTP proxy server with username and password authentication.
378 ///
379 /// # Arguments
380 ///
381 /// - `str` - The hostname or IP address of the proxy server.
382 /// - `u16` - The port number of the proxy server.
383 /// - `str` - The username for proxy authentication.
384 /// - `str` - The password for proxy authentication.
385 ///
386 /// # Returns
387 ///
388 /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
389 pub fn http_proxy_auth(
390 &mut self,
391 host: &str,
392 port: u16,
393 username: &str,
394 password: &str,
395 ) -> &mut Self {
396 if let Ok(mut config) = self.http_request.config.write() {
397 config.proxy = Some(ProxyConfig {
398 proxy_type: ProxyType::Http,
399 host: host.to_string(),
400 port,
401 username: Some(username.to_string()),
402 password: Some(password.to_string()),
403 });
404 }
405 self
406 }
407
408 /// Sets an HTTPS proxy with authentication for the request.
409 ///
410 /// This method configures the request to use an HTTPS proxy server with username and password authentication.
411 ///
412 /// # Arguments
413 ///
414 /// - `str` - The hostname or IP address of the proxy server.
415 /// - `u16` - The port number of the proxy server.
416 /// - `str` - The username for proxy authentication.
417 /// - `str` - The password for proxy authentication.
418 ///
419 /// # Returns
420 ///
421 /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
422 pub fn https_proxy_auth(
423 &mut self,
424 host: &str,
425 port: u16,
426 username: &str,
427 password: &str,
428 ) -> &mut Self {
429 if let Ok(mut config) = self.http_request.config.write() {
430 config.proxy = Some(ProxyConfig {
431 proxy_type: ProxyType::Https,
432 host: host.to_string(),
433 port,
434 username: Some(username.to_string()),
435 password: Some(password.to_string()),
436 });
437 }
438 self
439 }
440
441 /// Sets a SOCKS5 proxy with authentication for the request.
442 ///
443 /// This method configures the request to use a SOCKS5 proxy server with username and password authentication.
444 ///
445 /// # Arguments
446 ///
447 /// - `str` - The hostname or IP address of the proxy server.
448 /// - `u16` - The port number of the proxy server.
449 /// - `str` - The username for proxy authentication.
450 /// - `str` - The password for proxy authentication.
451 ///
452 /// # Returns
453 ///
454 /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
455 pub fn socks5_proxy_auth(
456 &mut self,
457 host: &str,
458 port: u16,
459 username: &str,
460 password: &str,
461 ) -> &mut Self {
462 if let Ok(mut config) = self.http_request.config.write() {
463 config.proxy = Some(ProxyConfig {
464 proxy_type: ProxyType::Socks5,
465 host: host.to_string(),
466 port,
467 username: Some(username.to_string()),
468 password: Some(password.to_string()),
469 });
470 }
471 self
472 }
473
474 /// Finalizes the builder and returns a fully constructed async `HttpRequest` instance.
475 ///
476 /// This method takes the current configuration stored in `http_request`, creates a new
477 /// `HttpRequest` instance with the configuration, and resets the builder's temporary
478 /// state for further use.
479 ///
480 /// # Returns
481 ///
482 /// - `BoxAsyncRequestTrait` - Returns a fully constructed `BoxAsyncRequestTrait` instance based on the current builder state.
483 pub fn build_async(&mut self) -> BoxAsyncRequestTrait {
484 self.builder = self.http_request.clone();
485 self.http_request = HttpRequest::default();
486 Box::new(self.builder.clone())
487 }
488
489 /// Finalizes the builder and returns a fully constructed synchronous `HttpRequest` instance.
490 ///
491 /// This method takes the current configuration stored in `http_request`, creates a new
492 /// `HttpRequest` instance with the configuration, and resets the builder's temporary
493 /// state for further use.
494 ///
495 /// # Returns
496 ///
497 /// - `BoxRequestTrait` - Returns a fully constructed `BoxRequestTrait` instance based on the current builder state.
498 pub fn build_sync(&mut self) -> BoxRequestTrait {
499 self.builder = self.http_request.clone();
500 self.http_request = HttpRequest::default();
501 Box::new(self.builder.clone())
502 }
503}