http_request/request/request_builder/
impl.rs

1use super::r#type::RequestBuilder;
2use crate::{
3    body::r#type::{Body, BodyBinary, BodyJson, BodyText},
4    request::{r#type::BoxRequestTrait, request::r#type::HttpRequest},
5};
6use http_type::*;
7use std::sync::Arc;
8
9impl Default for RequestBuilder {
10    fn default() -> Self {
11        Self {
12            http_request: HttpRequest::default(),
13            builder: HttpRequest::default(),
14        }
15    }
16}
17
18impl RequestBuilder {
19    /// Creates a new instance of the builder with default values.
20    ///
21    /// This method initializes the `RequestBuilder` with default values for all
22    /// fields.
23    ///
24    /// # Returns
25    /// Returns a new instance of `RequestBuilder`.
26    #[inline]
27    pub fn new() -> Self {
28        Self::default()
29    }
30
31    /// Sets the HTTP method for the request.
32    ///
33    /// This method allows you to specify the HTTP method (e.g., GET, POST) for the
34    /// request being built.
35    ///
36    /// # Parameters
37    /// - `methods`: The HTTP method to be set for the request.
38    ///
39    /// # Returns
40    /// Returns a mutable reference to the `RequestBuilder` to allow method chaining.
41    #[inline]
42    pub fn post(&mut self, url: &str) -> &mut Self {
43        self.http_request.methods = Arc::new(Methods::POST);
44        self.url(url);
45        self
46    }
47
48    /// Sets the HTTP method for the request.
49    ///
50    /// This method allows you to specify the HTTP method (e.g., GET, POST) for the
51    /// request being built.
52    ///
53    /// # Parameters
54    /// - `methods`: The HTTP method to be set for the request.
55    ///
56    /// # Returns
57    /// Returns a mutable reference to the `RequestBuilder` to allow method chaining.
58    #[inline]
59    pub fn get(&mut self, url: &str) -> &mut Self {
60        self.http_request.methods = Arc::new(Methods::GET);
61        self.url(url);
62        self
63    }
64
65    /// Sets the target URL of the request.
66    ///
67    /// This method allows you to specify the URL for the request being built.
68    ///
69    /// # Parameters
70    /// - `url`: The target URL of the request.
71    ///
72    /// # Returns
73    /// Returns a mutable reference to the `RequestBuilder` to allow method chaining.
74    #[inline]
75    fn url(&mut self, url: &str) -> &mut Self {
76        self.http_request.url = Arc::new(url.to_owned());
77        self
78    }
79
80    /// Sets the HTTP version to 1.1 for the request configuration.
81    ///
82    /// This method updates the HTTP version to `HTTP1_1` for the current
83    /// `http_request` configuration. It allows the user to force the
84    /// request to use HTTP 1.1 only, overriding any other version that may
85    /// have been previously set.
86    ///
87    /// # Returns
88    /// Returns a mutable reference to `self` to allow method chaining.
89    #[inline]
90    pub fn http1_1_only(&mut self) -> &mut Self {
91        if let Ok(mut config) = self.http_request.config.write() {
92            config.http_version = HttpVersion::HTTP1_1;
93        }
94        self
95    }
96
97    /// Sets the HTTP version to 2.0 for the request configuration.
98    ///
99    /// This method updates the HTTP version to `HTTP2` for the current
100    /// `http_request` configuration. It allows the user to force the
101    /// request to use HTTP 2.0 only, overriding any other version that may
102    /// have been previously set.
103    ///
104    /// # Returns
105    /// Returns a mutable reference to `self` to allow method chaining.
106    #[inline]
107    pub fn http2_only(&mut self) -> &mut Self {
108        if let Ok(mut config) = self.http_request.config.write() {
109            config.http_version = HttpVersion::HTTP2;
110        }
111        self
112    }
113
114    /// Sets the headers for the request.
115    ///
116    /// This method allows you to specify the headers for the request being built.
117    /// Existing headers may be merged with the provided ones.
118    ///
119    /// # Parameters
120    /// - `header`: The headers to be set for the request.
121    ///
122    /// # Returns
123    /// Returns a mutable reference to the `RequestBuilder` to allow method chaining.
124    #[inline]
125    pub fn headers<K, V, T>(&mut self, header: T) -> &mut Self
126    where
127        T: IntoIterator<Item = (K, V)>,
128        K: Into<String>,
129        V: Into<String>,
130    {
131        if let Some(tmp_header) = Arc::get_mut(&mut self.http_request.header) {
132            for (key, value) in header {
133                tmp_header.insert(key.into(), value.into());
134            }
135        }
136        self
137    }
138
139    /// Sets the JSON body of the request.
140    ///
141    /// This method allows you to set the body of the request as JSON data. If there is existing
142    /// body data, it will be replaced with the provided JSON data.
143    ///
144    /// # Parameters
145    /// - `body`: The JSON body data to be set for the request.
146    ///
147    /// # Returns
148    /// Returns a mutable reference to the `RequestBuilder` to allow method chaining.
149    #[inline]
150    pub fn json(&mut self, body: BodyJson) -> &mut Self {
151        self.http_request.body = Arc::new(Body::Json(body));
152        self
153    }
154
155    /// Sets the text body of the request.
156    ///
157    /// This method allows you to set the body of the request as plain text. If there is existing
158    /// body data, it will be replaced with the provided text data.
159    ///
160    /// # Parameters
161    /// - `body`: The text body data to be set for the request.
162    ///
163    /// # Returns
164    /// Returns a mutable reference to the `RequestBuilder` to allow method chaining.
165    #[inline]
166    pub fn text(&mut self, body: BodyText) -> &mut Self {
167        self.http_request.body = Arc::new(Body::Text(body));
168        self
169    }
170
171    /// Sets the HTTP request body to the given binary content.
172    ///
173    /// This method assigns the provided binary data to the body of the HTTP request.
174    /// The body is wrapped in an `Arc` to enable shared ownership and safe concurrency.
175    ///
176    /// # Parameters
177    ///
178    /// - `body` - A `BodyBinary` representing the binary content to be used as the HTTP request body.
179    ///
180    /// # Returns
181    ///
182    /// Returns a mutable reference to the current instance of the struct, allowing method chaining.
183    ///
184    /// # Notes
185    ///
186    /// This method overrides any previously set body. Use it when you want to assign binary content
187    /// specifically as the body of the HTTP request.
188    #[inline]
189    pub fn body(&mut self, body: BodyBinary) -> &mut Self {
190        self.http_request.body = Arc::new(Body::Binary(body));
191        self
192    }
193
194    /// Sets the timeout value for the current connection.
195    ///
196    /// This method sets the timeout duration for the connection, which is used to determine
197    /// how long the system should wait for a response before considering the connection attempt
198    /// as failed. The timeout value is stored in an `Arc` to allow it to be shared safely across
199    /// multiple threads if needed.
200    ///
201    /// # Parameters
202    ///
203    /// - `timeout`: The timeout duration in seconds. This value will be used to configure the
204    ///   connection timeout.
205    ///
206    /// # Returns
207    /// Returns a mutable reference to the `RequestBuilder` to allow method chaining.
208    #[inline]
209    pub fn timeout(&mut self, timeout: u64) -> &mut Self {
210        if let Ok(mut config) = self.http_request.config.write() {
211            config.timeout = timeout;
212        }
213        self
214    }
215
216    /// Enables HTTP redirection for the request.
217    ///
218    /// This method sets the `redirect` property of the `http_request` to `true`.
219    /// It returns a mutable reference to the current instance, allowing method chaining.
220    #[inline]
221    pub fn redirect(&mut self) -> &mut Self {
222        if let Ok(mut config) = self.http_request.config.write() {
223            config.redirect = true;
224        }
225        self
226    }
227
228    /// Unenables HTTP redirection for the request.
229    ///
230    /// This method sets the `redirect` property of the `http_request` to `false`.
231    /// It returns a mutable reference to the current instance, allowing method chaining.
232    #[inline]
233    pub fn unredirect(&mut self) -> &mut Self {
234        if let Ok(mut config) = self.http_request.config.write() {
235            config.redirect = false;
236        };
237        self
238    }
239
240    /// Sets the maximum number of allowed redirections for the HTTP request.
241    ///
242    /// This method updates the `max_redirect_times` field in the configuration and returns a mutable
243    /// reference to `self` to enable method chaining.
244    ///
245    /// # Parameters
246    ///
247    /// - `num` - The maximum number of redirections allowed. A value of `0` disables redirection.
248    ///
249    /// # Returns
250    ///
251    /// A mutable reference to the current instance for method chaining.
252    ///
253    /// # Notes
254    ///
255    /// Ensure that the value provided to `num` is within a valid range. Excessively high values
256    /// may lead to performance issues or unintended behavior.
257    #[inline]
258    pub fn max_redirect_times(&mut self, num: usize) -> &mut Self {
259        if let Ok(mut config) = self.http_request.config.write() {
260            config.max_redirect_times = num;
261        }
262        self
263    }
264
265    /// Sets the buffer size for the HTTP request configuration.
266    ///
267    /// This method allows you to set the size of the buffer used for reading
268    /// the HTTP response. It modifies the `buffer` field of the HTTP request's
269    /// configuration, which will be used when processing the response data.
270    ///
271    /// # Parameters
272    /// - `buffer`: The size of the buffer to be used, in bytes.
273    ///
274    /// # Returns
275    /// Returns a mutable reference to `self`, allowing for method chaining.
276    #[inline]
277    pub fn buffer(&mut self, buffer: usize) -> &mut Self {
278        if let Ok(mut config) = self.http_request.config.write() {
279            config.buffer = buffer;
280        }
281        self
282    }
283
284    /// Enables automatic response decoding.
285    ///
286    /// When enabled, the response body will be automatically decompressed if it is encoded
287    /// using a supported compression format (e.g., `gzip`, `deflate`, `br`).
288    ///
289    /// # Returns
290    /// A mutable reference to the current instance, allowing for method chaining.
291    #[inline]
292    pub fn decode(&mut self) -> &mut Self {
293        if let Ok(mut config) = self.http_request.config.write() {
294            config.decode = true;
295        }
296        self
297    }
298
299    /// Disables automatic response decoding.
300    ///
301    /// When disabled, the response body will not be automatically decompressed,
302    /// and the raw encoded data will be returned as-is.
303    ///
304    /// # Returns
305    /// A mutable reference to the current instance, allowing for method chaining.
306    #[inline]
307    pub fn undecode(&mut self) -> &mut Self {
308        if let Ok(mut config) = self.http_request.config.write() {
309            config.decode = false;
310        }
311        self
312    }
313
314    /// Finalizes the builder and returns a fully constructed `HttpRequest` instance.
315    ///
316    /// This method takes the current configuration stored in `http_request`, creates a new
317    /// `HttpRequest` instance with the configuration, and resets the builder's temporary
318    /// state for further use.
319    ///
320    /// # Returns
321    /// Returns a fully constructed `BoxRequestTrait` instance based on the current builder state.
322    #[inline]
323    pub fn build(&mut self) -> BoxRequestTrait {
324        self.builder = self.http_request.clone();
325        self.http_request = HttpRequest::default();
326        Box::new(self.builder.clone())
327    }
328}