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 {
118                    if let Some(existing_key) = existing_key {
119                        tmp_header.remove(&existing_key);
120                    }
121                }
122                let mut value_deque: VecDeque<String> = VecDeque::new();
123                value_deque.push_front(value_str);
124                tmp_header.insert(key_str, value_deque);
125            }
126        }
127        self
128    }
129
130    /// Sets JSON request body.
131    ///
132    /// # Arguments
133    ///
134    /// - `JsonValue` - The JSON body data.
135    ///
136    /// # Returns
137    ///
138    /// - `&mut RequestBuilder` - The builder for method chaining.
139    pub fn json(&mut self, body: JsonValue) -> &mut Self {
140        if let JsonValue::Object(map) = body {
141            let mut res_body: HashMapXxHash3_64<String, JsonValue> = hash_map_xx_hash3_64();
142            for (k, v) in map.iter() {
143                res_body.insert(k.to_string(), v.clone());
144            }
145            self.http_request.body = Arc::new(Body::Json(res_body));
146        }
147        self
148    }
149
150    /// Sets plain text request body.
151    ///
152    /// # Arguments
153    ///
154    /// - `T` - The text body data (must implement ToString).
155    ///
156    /// # Returns
157    ///
158    /// - `&mut RequestBuilder` - The builder for method chaining.
159    pub fn text<T: ToString>(&mut self, body: T) -> &mut Self {
160        self.http_request.body = Arc::new(Body::Text(body.to_string()));
161        self
162    }
163
164    /// Sets binary request body.
165    ///
166    /// # Arguments
167    ///
168    /// - `T` - The binary body data (must implement Into<Vec<u8>>).
169    ///
170    /// # Returns
171    ///
172    /// - `&mut RequestBuilder` - The builder for method chaining.
173    pub fn body<T: Into<Vec<u8>>>(&mut self, body: T) -> &mut Self {
174        self.http_request.body = Arc::new(Body::Binary(body.into()));
175        self
176    }
177
178    /// Sets the timeout value for the current connection.
179    ///
180    /// This method sets the timeout duration for the connection, which is used to determine
181    /// how long the system should wait for a response before considering the connection attempt
182    /// as failed. The timeout value is stored in an `Arc` to allow it to be shared safely across
183    /// multiple threads if needed.
184    ///
185    /// # Arguments
186    ///
187    /// - `u64` - The timeout duration in seconds. This value will be used to configure the
188    ///   connection timeout.
189    ///
190    /// # Returns
191    ///
192    /// - `&mut RequestBuilder` - The builder for method chaining.
193    pub fn timeout(&mut self, timeout: u64) -> &mut Self {
194        if let Ok(mut config) = self.http_request.config.write() {
195            config.timeout = timeout;
196        }
197        self
198    }
199
200    /// Enables HTTP redirection for the request.
201    ///
202    /// This method sets the `redirect` property of the `http_request` to `true`.
203    ///
204    /// # Returns
205    ///
206    /// - `&mut RequestBuilder` - The builder for method chaining.
207    pub fn redirect(&mut self) -> &mut Self {
208        if let Ok(mut config) = self.http_request.config.write() {
209            config.redirect = true;
210        }
211        self
212    }
213
214    /// Unenables HTTP redirection for the request.
215    ///
216    /// This method sets the `redirect` property of the `http_request` to `false`.
217    ///
218    /// # Returns
219    ///
220    /// - `&mut RequestBuilder` - The builder for method chaining.
221    pub fn unredirect(&mut self) -> &mut Self {
222        if let Ok(mut config) = self.http_request.config.write() {
223            config.redirect = false;
224        };
225        self
226    }
227
228    /// Sets the maximum number of allowed redirections for the HTTP request.
229    ///
230    /// This method updates the `max_redirect_times` field in the configuration and returns a mutable
231    /// reference to `self` to enable method chaining.
232    ///
233    /// # Arguments
234    ///
235    /// - `usize` - The maximum number of redirections allowed. A value of `0` disables redirection.
236    ///
237    /// # Returns
238    ///
239    /// - `&mut RequestBuilder` - A mutable reference to the current instance for method chaining.
240    ///
241    /// # Notes
242    ///
243    /// Ensure that the value provided to `num` is within a valid range. Excessively high values
244    /// may lead to performance issues or unintended behavior.
245    pub fn max_redirect_times(&mut self, num: usize) -> &mut Self {
246        if let Ok(mut config) = self.http_request.config.write() {
247            config.max_redirect_times = num;
248        }
249        self
250    }
251
252    /// Sets the buffer size for the HTTP request configuration.
253    ///
254    /// This method allows you to set the size of the buffer used for reading
255    /// the HTTP response. It modifies the `buffer` field of the HTTP request's
256    /// configuration, which will be used when processing the response data.
257    ///
258    /// # Arguments
259    ///
260    /// - `usize` - The size of the buffer to be used, in bytes.
261    ///
262    /// # Returns
263    ///
264    /// - `&mut RequestBuilder` - Returns a mutable reference to `self`, allowing for method chaining.
265    pub fn buffer(&mut self, buffer: usize) -> &mut Self {
266        if let Ok(mut config) = self.http_request.config.write() {
267            config.buffer = buffer;
268        }
269        self
270    }
271
272    /// Enables automatic response decoding.
273    ///
274    /// When enabled, the response body will be automatically decompressed if it is encoded
275    /// using a supported compression format.
276    ///
277    /// # Returns
278    ///
279    /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
280    pub fn decode(&mut self) -> &mut Self {
281        if let Ok(mut config) = self.http_request.config.write() {
282            config.decode = true;
283        }
284        self
285    }
286
287    /// Disables automatic response decoding.
288    ///
289    /// When disabled, the response body will not be automatically decompressed,
290    /// and the raw encoded data will be returned as-is.
291    ///
292    /// # Returns
293    ///
294    /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
295    pub fn undecode(&mut self) -> &mut Self {
296        if let Ok(mut config) = self.http_request.config.write() {
297            config.decode = false;
298        }
299        self
300    }
301
302    /// Sets an HTTP proxy for the request.
303    ///
304    /// This method configures the request to use an HTTP proxy server.
305    ///
306    /// # Arguments
307    ///
308    /// - `str` - The hostname or IP address of the proxy server.
309    /// - `u16` - The port number of the proxy server.
310    ///
311    /// # Returns
312    ///
313    /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
314    pub fn http_proxy(&mut self, host: &str, port: u16) -> &mut Self {
315        if let Ok(mut config) = self.http_request.config.write() {
316            config.proxy = Some(ProxyConfig {
317                proxy_type: ProxyType::Http,
318                host: host.to_string(),
319                port,
320                username: None,
321                password: None,
322            });
323        }
324        self
325    }
326
327    /// Sets an HTTPS proxy for the request.
328    ///
329    /// This method configures the request to use an HTTPS proxy server.
330    ///
331    /// # Arguments
332    ///
333    /// - `str` - The hostname or IP address of the proxy server.
334    /// - `u16` - The port number of the proxy server.
335    ///
336    /// # Returns
337    ///
338    /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
339    pub fn https_proxy(&mut self, host: &str, port: u16) -> &mut Self {
340        if let Ok(mut config) = self.http_request.config.write() {
341            config.proxy = Some(ProxyConfig {
342                proxy_type: ProxyType::Https,
343                host: host.to_string(),
344                port,
345                username: None,
346                password: None,
347            });
348        }
349        self
350    }
351
352    /// Sets a SOCKS5 proxy for the request.
353    ///
354    /// This method configures the request to use a SOCKS5 proxy server.
355    ///
356    /// # Arguments
357    ///
358    /// - `str` - The hostname or IP address of the proxy server.
359    /// - `u16` - The port number of the proxy server.
360    ///
361    /// # Returns
362    ///
363    /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
364    pub fn socks5_proxy(&mut self, host: &str, port: u16) -> &mut Self {
365        if let Ok(mut config) = self.http_request.config.write() {
366            config.proxy = Some(ProxyConfig {
367                proxy_type: ProxyType::Socks5,
368                host: host.to_string(),
369                port,
370                username: None,
371                password: None,
372            });
373        }
374        self
375    }
376
377    /// Sets an HTTP proxy with authentication for the request.
378    ///
379    /// This method configures the request to use an HTTP proxy server with username and password authentication.
380    ///
381    /// # Arguments
382    ///
383    /// - `str` - The hostname or IP address of the proxy server.
384    /// - `u16` - The port number of the proxy server.
385    /// - `str` - The username for proxy authentication.
386    /// - `str` - The password for proxy authentication.
387    ///
388    /// # Returns
389    ///
390    /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
391    pub fn http_proxy_auth(
392        &mut self,
393        host: &str,
394        port: u16,
395        username: &str,
396        password: &str,
397    ) -> &mut Self {
398        if let Ok(mut config) = self.http_request.config.write() {
399            config.proxy = Some(ProxyConfig {
400                proxy_type: ProxyType::Http,
401                host: host.to_string(),
402                port,
403                username: Some(username.to_string()),
404                password: Some(password.to_string()),
405            });
406        }
407        self
408    }
409
410    /// Sets an HTTPS proxy with authentication for the request.
411    ///
412    /// This method configures the request to use an HTTPS proxy server with username and password authentication.
413    ///
414    /// # Arguments
415    ///
416    /// - `str` - The hostname or IP address of the proxy server.
417    /// - `u16` - The port number of the proxy server.
418    /// - `str` - The username for proxy authentication.
419    /// - `str` - The password for proxy authentication.
420    ///
421    /// # Returns
422    ///
423    /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
424    pub fn https_proxy_auth(
425        &mut self,
426        host: &str,
427        port: u16,
428        username: &str,
429        password: &str,
430    ) -> &mut Self {
431        if let Ok(mut config) = self.http_request.config.write() {
432            config.proxy = Some(ProxyConfig {
433                proxy_type: ProxyType::Https,
434                host: host.to_string(),
435                port,
436                username: Some(username.to_string()),
437                password: Some(password.to_string()),
438            });
439        }
440        self
441    }
442
443    /// Sets a SOCKS5 proxy with authentication for the request.
444    ///
445    /// This method configures the request to use a SOCKS5 proxy server with username and password authentication.
446    ///
447    /// # Arguments
448    ///
449    /// - `str` - The hostname or IP address of the proxy server.
450    /// - `u16` - The port number of the proxy server.
451    /// - `str` - The username for proxy authentication.
452    /// - `str` - The password for proxy authentication.
453    ///
454    /// # Returns
455    ///
456    /// - `&mut RequestBuilder` - A mutable reference to the current instance, allowing for method chaining.
457    pub fn socks5_proxy_auth(
458        &mut self,
459        host: &str,
460        port: u16,
461        username: &str,
462        password: &str,
463    ) -> &mut Self {
464        if let Ok(mut config) = self.http_request.config.write() {
465            config.proxy = Some(ProxyConfig {
466                proxy_type: ProxyType::Socks5,
467                host: host.to_string(),
468                port,
469                username: Some(username.to_string()),
470                password: Some(password.to_string()),
471            });
472        }
473        self
474    }
475
476    /// Finalizes the builder and returns a fully constructed async `HttpRequest` instance.
477    ///
478    /// This method takes the current configuration stored in `http_request`, creates a new
479    /// `HttpRequest` instance with the configuration, and resets the builder's temporary
480    /// state for further use.
481    ///
482    /// # Returns
483    ///
484    /// - `BoxAsyncRequestTrait` - Returns a fully constructed `BoxAsyncRequestTrait` instance based on the current builder state.
485    pub fn build_async(&mut self) -> BoxAsyncRequestTrait {
486        self.builder = self.http_request.clone();
487        self.http_request = HttpRequest::default();
488        Box::new(self.builder.clone())
489    }
490
491    /// Finalizes the builder and returns a fully constructed synchronous `HttpRequest` instance.
492    ///
493    /// This method takes the current configuration stored in `http_request`, creates a new
494    /// `HttpRequest` instance with the configuration, and resets the builder's temporary
495    /// state for further use.
496    ///
497    /// # Returns
498    ///
499    /// - `BoxRequestTrait` - Returns a fully constructed `BoxRequestTrait` instance based on the current builder state.
500    pub fn build_sync(&mut self) -> BoxRequestTrait {
501        self.builder = self.http_request.clone();
502        self.http_request = HttpRequest::default();
503        Box::new(self.builder.clone())
504    }
505}