Skip to main content

http_request/request/request_builder/
impl.rs

1use super::*;
2
3/// Inherent implementation of [`RequestBuilder`].
4impl RequestBuilder {
5    /// Create an empty builder (defaults: GET, no headers, default config).
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - A fresh request builder with default settings.
10    pub fn new() -> Self {
11        Self::default()
12    }
13
14    /// Shortcut for `method(Method::Get)` + `url(url)`.
15    ///
16    /// # Arguments
17    ///
18    /// - `T` - A value convertible into the request URL, such as `&str` or `String`.
19    ///
20    /// # Returns
21    ///
22    /// - `&mut Self` - A mutable reference to this builder for chaining.
23    pub fn get<T>(&mut self, url: T) -> &mut Self
24    where
25        T: Into<String>,
26    {
27        self.get_mut_request().set_method(Method::Get);
28        self.get_mut_request().set_url(url);
29        self
30    }
31
32    /// Shortcut for `method(Method::Post)` + `url(url)`.
33    ///
34    /// # Arguments
35    ///
36    /// - `T` - A value convertible into the request URL, such as `&str` or `String`.
37    ///
38    /// # Returns
39    ///
40    /// - `&mut Self` - A mutable reference to this builder for chaining.
41    pub fn post<T>(&mut self, url: T) -> &mut Self
42    where
43        T: Into<String>,
44    {
45        self.get_mut_request().set_method(Method::Post);
46        self.get_mut_request().set_url(url);
47        self
48    }
49
50    /// Shortcut for `method(Method::Put)` + `url(url)`.
51    ///
52    /// # Arguments
53    ///
54    /// - `T` - A value convertible into the request URL, such as `&str` or `String`.
55    ///
56    /// # Returns
57    ///
58    /// - `&mut Self` - A mutable reference to this builder for chaining.
59    pub fn put<T>(&mut self, url: T) -> &mut Self
60    where
61        T: Into<String>,
62    {
63        self.get_mut_request().set_method(Method::Put);
64        self.get_mut_request().set_url(url);
65        self
66    }
67
68    /// Shortcut for `method(Method::Delete)` + `url(url)`.
69    ///
70    /// # Arguments
71    ///
72    /// - `T` - A value convertible into the request URL, such as `&str` or `String`.
73    ///
74    /// # Returns
75    ///
76    /// - `&mut Self` - A mutable reference to this builder for chaining.
77    pub fn delete<T>(&mut self, url: T) -> &mut Self
78    where
79        T: Into<String>,
80    {
81        self.get_mut_request().set_method(Method::Delete);
82        self.get_mut_request().set_url(url);
83        self
84    }
85
86    /// Shortcut for `method(Method::Patch)` + `url(url)`.
87    ///
88    /// # Arguments
89    ///
90    /// - `T` - A value convertible into the request URL, such as `&str` or `String`.
91    ///
92    /// # Returns
93    ///
94    /// - `&mut Self` - A mutable reference to this builder for chaining.
95    pub fn patch<T>(&mut self, url: T) -> &mut Self
96    where
97        T: Into<String>,
98    {
99        self.get_mut_request().set_method(Method::Patch);
100        self.get_mut_request().set_url(url);
101        self
102    }
103
104    /// Shortcut for `method(Method::Head)` + `url(url)`.
105    ///
106    /// # Arguments
107    ///
108    /// - `T` - A value convertible into the request URL, such as `&str` or `String`.
109    ///
110    /// # Returns
111    ///
112    /// - `&mut Self` - A mutable reference to this builder for chaining.
113    pub fn head<T>(&mut self, url: T) -> &mut Self
114    where
115        T: Into<String>,
116    {
117        self.get_mut_request().set_method(Method::Head);
118        self.get_mut_request().set_url(url);
119        self
120    }
121
122    /// Shortcut for `method(Method::Options)` + `url(url)`.
123    ///
124    /// # Arguments
125    ///
126    /// - `T` - A value convertible into the request URL, such as `&str` or `String`.
127    ///
128    /// # Returns
129    ///
130    /// - `&mut Self` - A mutable reference to this builder for chaining.
131    pub fn options<T>(&mut self, url: T) -> &mut Self
132    where
133        T: Into<String>,
134    {
135        self.get_mut_request().set_method(Method::Options);
136        self.get_mut_request().set_url(url);
137        self
138    }
139
140    /// Set HTTP method explicitly (`Method::Get` / `Method::Post` / etc.).
141    ///
142    /// # Arguments
143    ///
144    /// - `Method` - The HTTP method to apply to the request.
145    ///
146    /// # Returns
147    ///
148    /// - `&mut Self` - A mutable reference to this builder for chaining.
149    pub fn method(&mut self, method: Method) -> &mut Self {
150        self.get_mut_request().set_method(method);
151        self
152    }
153
154    /// Set URL.
155    ///
156    /// # Arguments
157    ///
158    /// - `T` - A value convertible into the request URL, such as `&str` or `String`.
159    ///
160    /// # Returns
161    ///
162    /// - `&mut Self` - A mutable reference to this builder for chaining.
163    pub fn url<T>(&mut self, url: T) -> &mut Self
164    where
165        T: Into<String>,
166    {
167        self.get_mut_request().set_url(url);
168        self
169    }
170
171    /// Append a percent-encoded query parameter to the request URL.
172    ///
173    /// # Arguments
174    ///
175    /// - `K` - The query parameter name.
176    /// - `V` - The query parameter value.
177    ///
178    /// # Returns
179    ///
180    /// - `&mut Self` - A mutable reference to this builder for chaining.
181    pub fn query<K, V>(&mut self, key: K, value: V) -> &mut Self
182    where
183        K: AsRef<str>,
184        V: AsRef<str>,
185    {
186        let current: String = self.get_request().get_url().clone();
187        let (base, fragment): (&str, Option<&str>) = match current.split_once(URL_FRAGMENT) {
188            Some((prefix, frag)) => (prefix, Some(frag)),
189            None => (current.as_str(), None),
190        };
191        let sep: char = if base.contains(URL_QUERY) {
192            if base.ends_with(URL_QUERY) || base.ends_with('&') {
193                '\0'
194            } else {
195                '&'
196            }
197        } else {
198            URL_QUERY
199        };
200        let mut updated: String = String::with_capacity(
201            current.len() + key.as_ref().len() * 3 + value.as_ref().len() * 3 + 2,
202        );
203        updated.push_str(base);
204        if sep != '\0' {
205            updated.push(sep);
206        }
207        push_percent_encoded(key.as_ref(), &mut updated);
208        updated.push('=');
209        push_percent_encoded(value.as_ref(), &mut updated);
210        if let Some(frag) = fragment {
211            updated.push(URL_FRAGMENT);
212            updated.push_str(frag);
213        }
214        self.get_mut_request().set_url(updated);
215        self
216    }
217
218    /// Append multiple percent-encoded query parameters to the request URL.
219    ///
220    /// # Arguments
221    ///
222    /// - `I` - Iterator yielding `(key, value)` pairs.
223    ///
224    /// # Returns
225    ///
226    /// - `&mut Self` - A mutable reference to this builder for chaining.
227    pub fn query_pairs<I, K, V>(&mut self, pairs: I) -> &mut Self
228    where
229        I: IntoIterator<Item = (K, V)>,
230        K: AsRef<str>,
231        V: AsRef<str>,
232    {
233        for (key, value) in pairs {
234            self.query(key, value);
235        }
236        self
237    }
238
239    /// Set a single header (last write wins on duplicate keys).
240    ///
241    /// # Arguments
242    ///
243    /// - `K` - A header name that can be borrowed as a string slice.
244    /// - `V` - A header value that can be borrowed as a string slice.
245    ///
246    /// # Returns
247    ///
248    /// - `&mut Self` - A mutable reference to this builder for chaining.
249    pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self
250    where
251        K: AsRef<str>,
252        V: AsRef<str>,
253    {
254        self.get_mut_request().set_header(key, value);
255        self
256    }
257
258    /// Set many headers at once.
259    ///
260    /// # Arguments
261    ///
262    /// - `HashMap<K, V>` - The header name-value pairs to apply, where each name and
263    ///   value can be borrowed as a string slice.
264    ///
265    /// # Returns
266    ///
267    /// - `&mut Self` - A mutable reference to this builder for chaining.
268    pub fn headers<K, V>(&mut self, headers: HashMap<K, V>) -> &mut Self
269    where
270        K: AsRef<str>,
271        V: AsRef<str>,
272    {
273        for (k, v) in headers {
274            self.get_mut_request().set_header(k, v);
275        }
276        self
277    }
278
279    /// Set an `Authorization: Bearer <token>` header.
280    ///
281    /// # Arguments
282    ///
283    /// - `T` - The bearer token string.
284    ///
285    /// # Returns
286    ///
287    /// - `&mut Self` - A mutable reference to this builder for chaining.
288    pub fn bearer_auth<T>(&mut self, token: T) -> &mut Self
289    where
290        T: AsRef<str>,
291    {
292        let value: String = format!("{BEARER_PREFIX}{}", token.as_ref());
293        self.get_mut_request()
294            .set_header(HEADER_AUTHORIZATION, value);
295        self
296    }
297
298    /// Set an `Authorization: Basic <base64(username:password)>` header.
299    ///
300    /// # Arguments
301    ///
302    /// - `U` - The username string.
303    /// - `P` - The password string.
304    ///
305    /// # Returns
306    ///
307    /// - `&mut Self` - A mutable reference to this builder for chaining.
308    pub fn basic_auth<U, P>(&mut self, username: U, password: P) -> &mut Self
309    where
310        U: AsRef<str>,
311        P: AsRef<str>,
312    {
313        let raw: String = format!("{}:{}", username.as_ref(), password.as_ref());
314        let encoded: String = crate::utils::base64_encode(raw.as_bytes());
315        let value: String = format!("{BASIC_PREFIX}{encoded}");
316        self.get_mut_request()
317            .set_header(HEADER_AUTHORIZATION, value);
318        self
319    }
320
321    /// Append a `name=value` cookie to the outgoing `Cookie` header.
322    ///
323    /// # Arguments
324    ///
325    /// - `K` - Cookie name.
326    /// - `V` - Cookie value.
327    ///
328    /// # Returns
329    ///
330    /// - `&mut Self` - A mutable reference to this builder for chaining.
331    pub fn cookie<K, V>(&mut self, name: K, value: V) -> &mut Self
332    where
333        K: AsRef<str>,
334        V: AsRef<str>,
335    {
336        let pair: String = format!("{}={}", name.as_ref(), value.as_ref());
337        let existing: Option<String> = self
338            .get_request()
339            .get_headers()
340            .iter()
341            .find(|(k, _): &(&String, &String)| k.eq_ignore_ascii_case(COOKIE))
342            .map(|(_, v): (&String, &String)| v.clone());
343        let merged: String = match existing {
344            Some(prev) if !prev.is_empty() => format!("{prev}; {pair}"),
345            _ => pair,
346        };
347        self.get_mut_request().set_header(COOKIE, merged);
348        self
349    }
350
351    /// Remove a header by key.
352    ///
353    /// # Arguments
354    ///
355    /// - `K` - The header name to remove, which can be borrowed as a string slice.
356    ///
357    /// # Returns
358    ///
359    /// - `&mut Self` - A mutable reference to this builder for chaining.
360    pub fn remove_header<K>(&mut self, key: K) -> &mut Self
361    where
362        K: AsRef<str>,
363    {
364        self.get_mut_request().remove_header(key);
365        self
366    }
367
368    /// Clear all headers.
369    ///
370    /// # Returns
371    ///
372    /// - `&mut Self` - A mutable reference to this builder for chaining.
373    pub fn clear_headers(&mut self) -> &mut Self {
374        self.get_mut_request().clear_headers();
375        self
376    }
377
378    /// Set raw body bytes.
379    ///
380    /// # Arguments
381    ///
382    /// - `B` - A value convertible into the raw body bytes, such as `Vec<u8>` or
383    ///   `&[u8]`.
384    ///
385    /// # Returns
386    ///
387    /// - `&mut Self` - A mutable reference to this builder for chaining.
388    pub fn body<B>(&mut self, bytes: B) -> &mut Self
389    where
390        B: Into<Vec<u8>>,
391    {
392        self.get_mut_request().set_body(Body::from_bytes(bytes));
393        self
394    }
395
396    /// Set UTF-8 text body.
397    ///
398    /// # Arguments
399    ///
400    /// - `T` - A value convertible into the text body, such as `&str` or `String`.
401    ///
402    /// # Returns
403    ///
404    /// - `&mut Self` - A mutable reference to this builder for chaining.
405    pub fn body_text<T>(&mut self, text: T) -> &mut Self
406    where
407        T: Into<String>,
408    {
409        self.get_mut_request()
410            .set_body(Body::from_bytes(text.into().into_bytes()));
411        self
412    }
413
414    /// Set JSON body (serialised via `serde_json`).
415    ///
416    /// # Arguments
417    ///
418    /// - `&V` - A reference to the value to serialise as the JSON body.
419    ///
420    /// # Returns
421    ///
422    /// - `&mut Self` - A mutable reference to this builder for chaining.
423    pub fn body_json<V>(&mut self, value: &V) -> &mut Self
424    where
425        V: Serialize,
426    {
427        if let Ok(bytes) = to_vec(value) {
428            self.get_mut_request().set_body(Body::from_bytes(bytes));
429        }
430        self
431    }
432
433    /// Serializes `value` as JSON, sets `Content-Type: application/json` if absent, and propagates serialization errors.
434    ///
435    /// # Arguments
436    ///
437    /// - `&V` - Reference to the serializable JSON payload.
438    ///
439    /// # Returns
440    ///
441    /// - `Result<&mut Self, RequestError>` - Updated builder or serialization error.
442    pub fn try_body_json<V>(&mut self, value: &V) -> Result<&mut Self, RequestError>
443    where
444        V: Serialize,
445    {
446        let bytes: Vec<u8> = match to_vec(value) {
447            Ok(bytes) => bytes,
448            Err(err) => return Err(RequestError::Request(err.to_string())),
449        };
450        let has_ct: bool = self
451            .get_request()
452            .get_headers()
453            .keys()
454            .any(|key: &String| key.eq_ignore_ascii_case(CONTENT_TYPE));
455        if !has_ct {
456            self.get_mut_request()
457                .set_header(CONTENT_TYPE, JSON_CONTENT_TYPE);
458        }
459        self.get_mut_request().set_body(Body::from_bytes(bytes));
460        Ok(self)
461    }
462
463    /// Set an `application/x-www-form-urlencoded` body and matching `Content-Type` header.
464    ///
465    /// # Arguments
466    ///
467    /// - `I` - Iterator yielding `(key, value)` form fields.
468    ///
469    /// # Returns
470    ///
471    /// - `&mut Self` - A mutable reference to this builder for chaining.
472    pub fn body_form<I, K, V>(&mut self, fields: I) -> &mut Self
473    where
474        I: IntoIterator<Item = (K, V)>,
475        K: AsRef<str>,
476        V: AsRef<str>,
477    {
478        let mut encoded: String = String::new();
479        for (key, value) in fields {
480            if !encoded.is_empty() {
481                encoded.push('&');
482            }
483            push_percent_encoded(key.as_ref(), &mut encoded);
484            encoded.push('=');
485            push_percent_encoded(value.as_ref(), &mut encoded);
486        }
487        self.get_mut_request()
488            .set_header(CONTENT_TYPE, FORM_URLENCODED_CONTENT_TYPE);
489        self.get_mut_request()
490            .set_body(Body::from_bytes(encoded.into_bytes()));
491        self
492    }
493
494    /// Set an RFC 7578 `multipart/form-data` body from `http_type::BodyPart` entries.
495    ///
496    /// # Arguments
497    ///
498    /// - `&[BodyPart]` - Multipart fields and uploaded file parts.
499    ///
500    /// # Returns
501    ///
502    /// - `&mut Self` - A mutable reference to this builder for chaining.
503    pub fn body_multipart(&mut self, parts: &[BodyPart]) -> &mut Self {
504        let (content_type, bytes): (String, Vec<u8>) = encode_multipart_parts(parts);
505        self.get_mut_request()
506            .set_header(CONTENT_TYPE, content_type);
507        self.get_mut_request().set_body(Body::from_bytes(bytes));
508        self
509    }
510
511    /// Add one or more PEM-encoded root CA certificates for TLS verification.
512    ///
513    /// # Arguments
514    ///
515    /// - `&[u8]` - Raw PEM-encoded X.509 certificate bytes.
516    ///
517    /// # Returns
518    ///
519    /// - `Result<&mut Self, RequestError>` - Updated builder or an error when PEM parsing fails.
520    pub fn root_cert_pem(&mut self, pem_bytes: &[u8]) -> Result<&mut Self, RequestError> {
521        let roots: &mut RootCertStore = self.get_mut_request().get_mut_tmp().root_cert_or_init();
522        let _: usize = add_pem_certs_to_store(roots, pem_bytes)?;
523        Ok(self)
524    }
525
526    /// Set request timeout in milliseconds.
527    ///
528    /// # Arguments
529    ///
530    /// - `u64` - The request timeout in milliseconds.
531    ///
532    /// # Returns
533    ///
534    /// - `&mut Self` - A mutable reference to this builder for chaining.
535    pub fn timeout(&mut self, ms: u64) -> &mut Self {
536        self.get_mut_request().get_mut_config().set_timeout(ms);
537        self
538    }
539
540    /// Set dedicated TCP connect timeout in milliseconds (`0` inherits `timeout`).
541    ///
542    /// # Arguments
543    ///
544    /// - `u64` - The connect timeout in milliseconds.
545    ///
546    /// # Returns
547    ///
548    /// - `&mut Self` - A mutable reference to this builder for chaining.
549    pub fn connect_timeout(&mut self, ms: u64) -> &mut Self {
550        self.get_mut_request()
551            .get_mut_config()
552            .set_connect_timeout(ms);
553        self
554    }
555
556    /// Configure automatic bounded retries for idempotent transient failures (`0` = disabled).
557    ///
558    /// # Arguments
559    ///
560    /// - `usize` - Maximum number of retry attempts.
561    ///
562    /// # Returns
563    ///
564    /// - `&mut Self` - A mutable reference to this builder for chaining.
565    pub fn retry(&mut self, max_retries: usize) -> &mut Self {
566        self.get_mut_request()
567            .get_mut_config()
568            .set_max_retries(max_retries);
569        self
570    }
571
572    /// Enable or disable HTTP keep-alive connection pooling for this request.
573    ///
574    /// # Arguments
575    ///
576    /// - `bool` - `true` to reuse persistent HTTP/1.1 or HTTP/2 connections from the pool, `false` to close after use.
577    ///
578    /// # Returns
579    ///
580    /// - `&mut Self` - A mutable reference to this builder for chaining.
581    pub fn keep_alive(&mut self, enabled: bool) -> &mut Self {
582        self.get_mut_request()
583            .get_mut_config()
584            .set_keep_alive(enabled);
585        self
586    }
587
588    /// Set per-read buffer size.
589    ///
590    /// # Arguments
591    ///
592    /// - `usize` - The per-read buffer size in bytes.
593    ///
594    /// # Returns
595    ///
596    /// - `&mut Self` - A mutable reference to this builder for chaining.
597    pub fn buffer_size(&mut self, n: usize) -> &mut Self {
598        self.get_mut_request().get_mut_config().set_buffer_size(n);
599        self
600    }
601
602    /// Force HTTP/1.1.
603    ///
604    /// # Returns
605    ///
606    /// - `&mut Self` - A mutable reference to this builder for chaining.
607    pub fn http1_1_only(&mut self) -> &mut Self {
608        self.get_mut_request()
609            .get_mut_config()
610            .set_http_version(HttpVersion::Http1_1);
611        self
612    }
613
614    /// Force HTTP/2.
615    ///
616    /// # Returns
617    ///
618    /// - `&mut Self` - A mutable reference to this builder for chaining.
619    pub fn http2_only(&mut self) -> &mut Self {
620        self.get_mut_request()
621            .get_mut_config()
622            .set_http_version(HttpVersion::Http2);
623        self
624    }
625
626    /// Enable auto-follow of 3xx redirects.
627    ///
628    /// # Returns
629    ///
630    /// - `&mut Self` - A mutable reference to this builder for chaining.
631    pub fn redirect(&mut self) -> &mut Self {
632        self.get_mut_request().get_mut_config().set_redirect(true);
633        self
634    }
635
636    /// Disable auto-follow of 3xx redirects (default).
637    ///
638    /// # Returns
639    ///
640    /// - `&mut Self` - A mutable reference to this builder for chaining.
641    pub fn no_redirect(&mut self) -> &mut Self {
642        self.get_mut_request().get_mut_config().set_redirect(false);
643        self
644    }
645
646    /// Maximum number of redirects to follow (default `DEFAULT_MAX_REDIRECT_TIMES`).
647    ///
648    /// # Arguments
649    ///
650    /// - `usize` - The maximum number of redirects to follow.
651    ///
652    /// # Returns
653    ///
654    /// - `&mut Self` - A mutable reference to this builder for chaining.
655    pub fn max_redirect_times(&mut self, n: usize) -> &mut Self {
656        self.get_mut_request()
657            .get_mut_config()
658            .set_max_redirect_times(n);
659        self
660    }
661
662    /// Enable automatic response body decompression (gzip / deflate / br).
663    ///
664    /// # Returns
665    ///
666    /// - `&mut Self` - A mutable reference to this builder for chaining.
667    pub fn decode(&mut self) -> &mut Self {
668        self.get_mut_request().get_mut_config().set_decode(true);
669        self
670    }
671
672    /// Disable automatic response body decompression.
673    ///
674    /// # Returns
675    ///
676    /// - `&mut Self` - A mutable reference to this builder for chaining.
677    pub fn no_decode(&mut self) -> &mut Self {
678        self.get_mut_request().get_mut_config().set_decode(false);
679        self
680    }
681
682    /// Set the proxy configuration. Pass `None` (via [`Proxy::default()`) to
683    /// clear an existing proxy.
684    ///
685    /// Construct via [`Proxy::http`] / [`Proxy::https`] / [`Proxy::socks5`]
686    /// and optionally chain `.auth(user, pass)`.
687    ///
688    /// # Arguments
689    ///
690    /// - `Proxy` - The proxy configuration to apply to the request.
691    ///
692    /// # Returns
693    ///
694    /// - `&mut Self` - A mutable reference to this builder for chaining.
695    pub fn proxy(&mut self, proxy: Proxy) -> &mut Self {
696        self.get_mut_request()
697            .get_mut_config()
698            .set_proxy(Some(proxy));
699        self
700    }
701
702    /// Clear the proxy (use direct connection).
703    ///
704    /// # Returns
705    ///
706    /// - `&mut Self` - A mutable reference to this builder for chaining.
707    pub fn no_proxy(&mut self) -> &mut Self {
708        self.get_mut_request().get_mut_config().set_proxy(None);
709        self
710    }
711
712    /// Finalise the builder and return the [`HttpRequest`].
713    ///
714    /// # Returns
715    ///
716    /// - `HttpRequest` - The finalised request, leaving the builder empty.
717    pub fn build(&mut self) -> HttpRequest {
718        mem::take(self.get_mut_request())
719    }
720
721    /// Finalises the builder and sends the request synchronously in one step.
722    ///
723    /// # Returns
724    ///
725    /// - `Result<HttpResponse, RequestError>` - Parsed HTTP response or error.
726    #[inline]
727    pub fn send(&mut self) -> Result<HttpResponse, RequestError> {
728        let mut request: HttpRequest = self.build();
729        request.send()
730    }
731
732    /// Finalises the builder and sends the request asynchronously in one step.
733    ///
734    /// # Returns
735    ///
736    /// - `Result<HttpResponse, RequestError>` - Parsed HTTP response or error.
737    #[inline]
738    pub async fn send_async(&mut self) -> Result<HttpResponse, RequestError> {
739        let mut request: HttpRequest = self.build();
740        request.send_async().await
741    }
742}