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    /// Set an `application/x-www-form-urlencoded` body and matching `Content-Type` header.
434    ///
435    /// # Arguments
436    ///
437    /// - `I` - Iterator yielding `(key, value)` form fields.
438    ///
439    /// # Returns
440    ///
441    /// - `&mut Self` - A mutable reference to this builder for chaining.
442    pub fn body_form<I, K, V>(&mut self, fields: I) -> &mut Self
443    where
444        I: IntoIterator<Item = (K, V)>,
445        K: AsRef<str>,
446        V: AsRef<str>,
447    {
448        let mut encoded: String = String::new();
449        for (key, value) in fields {
450            if !encoded.is_empty() {
451                encoded.push('&');
452            }
453            push_percent_encoded(key.as_ref(), &mut encoded);
454            encoded.push('=');
455            push_percent_encoded(value.as_ref(), &mut encoded);
456        }
457        self.get_mut_request()
458            .set_header(CONTENT_TYPE, FORM_URLENCODED_CONTENT_TYPE);
459        self.get_mut_request()
460            .set_body(Body::from_bytes(encoded.into_bytes()));
461        self
462    }
463
464    /// Set an RFC 7578 `multipart/form-data` body from `http_type::BodyPart` entries.
465    ///
466    /// # Arguments
467    ///
468    /// - `&[BodyPart]` - Multipart fields and uploaded file parts.
469    ///
470    /// # Returns
471    ///
472    /// - `&mut Self` - A mutable reference to this builder for chaining.
473    pub fn body_multipart(&mut self, parts: &[BodyPart]) -> &mut Self {
474        let (content_type, bytes): (String, Vec<u8>) = encode_multipart_parts(parts);
475        self.get_mut_request()
476            .set_header(CONTENT_TYPE, content_type);
477        self.get_mut_request().set_body(Body::from_bytes(bytes));
478        self
479    }
480
481    /// Add one or more PEM-encoded root CA certificates for TLS verification.
482    ///
483    /// # Arguments
484    ///
485    /// - `&[u8]` - Raw PEM-encoded X.509 certificate bytes.
486    ///
487    /// # Returns
488    ///
489    /// - `Result<&mut Self, RequestError>` - Updated builder or an error when PEM parsing fails.
490    pub fn root_cert_pem(&mut self, pem_bytes: &[u8]) -> Result<&mut Self, RequestError> {
491        let roots: &mut RootCertStore = self.get_mut_request().get_mut_tmp().get_mut_root_cert();
492        let _: usize = add_pem_certs_to_store(roots, pem_bytes)?;
493        Ok(self)
494    }
495
496    /// Set request timeout in milliseconds.
497    ///
498    /// # Arguments
499    ///
500    /// - `u64` - The request timeout in milliseconds.
501    ///
502    /// # Returns
503    ///
504    /// - `&mut Self` - A mutable reference to this builder for chaining.
505    pub fn timeout(&mut self, ms: u64) -> &mut Self {
506        self.get_mut_request().get_mut_config().set_timeout(ms);
507        self
508    }
509
510    /// Set dedicated TCP connect timeout in milliseconds (`0` inherits `timeout`).
511    ///
512    /// # Arguments
513    ///
514    /// - `u64` - The connect timeout in milliseconds.
515    ///
516    /// # Returns
517    ///
518    /// - `&mut Self` - A mutable reference to this builder for chaining.
519    pub fn connect_timeout(&mut self, ms: u64) -> &mut Self {
520        self.get_mut_request()
521            .get_mut_config()
522            .set_connect_timeout(ms);
523        self
524    }
525
526    /// Configure automatic bounded retries for idempotent transient failures (`0` = disabled).
527    ///
528    /// # Arguments
529    ///
530    /// - `usize` - Maximum number of retry attempts.
531    ///
532    /// # Returns
533    ///
534    /// - `&mut Self` - A mutable reference to this builder for chaining.
535    pub fn retry(&mut self, max_retries: usize) -> &mut Self {
536        self.get_mut_request()
537            .get_mut_config()
538            .set_max_retries(max_retries);
539        self
540    }
541
542    /// Enable or disable HTTP keep-alive connection pooling for this request.
543    ///
544    /// # Arguments
545    ///
546    /// - `bool` - `true` to reuse persistent HTTP/1.1 or HTTP/2 connections from the pool, `false` to close after use.
547    ///
548    /// # Returns
549    ///
550    /// - `&mut Self` - A mutable reference to this builder for chaining.
551    pub fn keep_alive(&mut self, enabled: bool) -> &mut Self {
552        self.get_mut_request()
553            .get_mut_config()
554            .set_keep_alive(enabled);
555        self
556    }
557
558    /// Set per-read buffer size.
559    ///
560    /// # Arguments
561    ///
562    /// - `usize` - The per-read buffer size in bytes.
563    ///
564    /// # Returns
565    ///
566    /// - `&mut Self` - A mutable reference to this builder for chaining.
567    pub fn buffer_size(&mut self, n: usize) -> &mut Self {
568        self.get_mut_request().get_mut_config().set_buffer_size(n);
569        self
570    }
571
572    /// Force HTTP/1.1.
573    ///
574    /// # Returns
575    ///
576    /// - `&mut Self` - A mutable reference to this builder for chaining.
577    pub fn http1_1_only(&mut self) -> &mut Self {
578        self.get_mut_request()
579            .get_mut_config()
580            .set_http_version(HttpVersion::Http1_1);
581        self
582    }
583
584    /// Force HTTP/2.
585    ///
586    /// # Returns
587    ///
588    /// - `&mut Self` - A mutable reference to this builder for chaining.
589    pub fn http2_only(&mut self) -> &mut Self {
590        self.get_mut_request()
591            .get_mut_config()
592            .set_http_version(HttpVersion::Http2);
593        self
594    }
595
596    /// Enable auto-follow of 3xx redirects.
597    ///
598    /// # Returns
599    ///
600    /// - `&mut Self` - A mutable reference to this builder for chaining.
601    pub fn redirect(&mut self) -> &mut Self {
602        self.get_mut_request().get_mut_config().set_redirect(true);
603        self
604    }
605
606    /// Disable auto-follow of 3xx redirects (default).
607    ///
608    /// # Returns
609    ///
610    /// - `&mut Self` - A mutable reference to this builder for chaining.
611    pub fn no_redirect(&mut self) -> &mut Self {
612        self.get_mut_request().get_mut_config().set_redirect(false);
613        self
614    }
615
616    /// Maximum number of redirects to follow (default `DEFAULT_MAX_REDIRECT_TIMES`).
617    ///
618    /// # Arguments
619    ///
620    /// - `usize` - The maximum number of redirects to follow.
621    ///
622    /// # Returns
623    ///
624    /// - `&mut Self` - A mutable reference to this builder for chaining.
625    pub fn max_redirect_times(&mut self, n: usize) -> &mut Self {
626        self.get_mut_request()
627            .get_mut_config()
628            .set_max_redirect_times(n);
629        self
630    }
631
632    /// Enable automatic response body decompression (gzip / deflate / br).
633    ///
634    /// # Returns
635    ///
636    /// - `&mut Self` - A mutable reference to this builder for chaining.
637    pub fn decode(&mut self) -> &mut Self {
638        self.get_mut_request().get_mut_config().set_decode(true);
639        self
640    }
641
642    /// Disable automatic response body decompression.
643    ///
644    /// # Returns
645    ///
646    /// - `&mut Self` - A mutable reference to this builder for chaining.
647    pub fn no_decode(&mut self) -> &mut Self {
648        self.get_mut_request().get_mut_config().set_decode(false);
649        self
650    }
651
652    /// Set the proxy configuration. Pass `None` (via [`Proxy::default()`) to
653    /// clear an existing proxy.
654    ///
655    /// Construct via [`Proxy::http`] / [`Proxy::https`] / [`Proxy::socks5`]
656    /// and optionally chain `.auth(user, pass)`.
657    ///
658    /// # Arguments
659    ///
660    /// - `Proxy` - The proxy configuration to apply to the request.
661    ///
662    /// # Returns
663    ///
664    /// - `&mut Self` - A mutable reference to this builder for chaining.
665    pub fn proxy(&mut self, proxy: Proxy) -> &mut Self {
666        self.get_mut_request()
667            .get_mut_config()
668            .set_proxy(Some(proxy));
669        self
670    }
671
672    /// Clear the proxy (use direct connection).
673    ///
674    /// # Returns
675    ///
676    /// - `&mut Self` - A mutable reference to this builder for chaining.
677    pub fn no_proxy(&mut self) -> &mut Self {
678        self.get_mut_request().get_mut_config().set_proxy(None);
679        self
680    }
681
682    /// Finalise the builder and return the [`HttpRequest`].
683    ///
684    /// # Returns
685    ///
686    /// - `HttpRequest` - The finalised request, leaving the builder empty.
687    pub fn build(&mut self) -> HttpRequest {
688        mem::take(self.get_mut_request())
689    }
690}