http_request/request/request_builder/
impl.rs

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