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