http_type/response/
impl.rs

1use crate::*;
2
3/// Provides a default value for `Response`.
4///
5/// Returns a new `Response` instance with all fields initialized to their default values.
6impl Default for Response {
7    #[inline(always)]
8    fn default() -> Self {
9        let http_status: HttpStatus = HttpStatus::default();
10        Self {
11            version: HttpVersion::HTTP1_1,
12            status_code: http_status.code(),
13            reason_phrase: http_status.to_string(),
14            headers: hash_map_xx_hash3_64(),
15            body: Vec::new(),
16        }
17    }
18}
19
20impl Response {
21    /// Creates a new instance of `Response`.
22    ///
23    /// # Returns
24    ///
25    /// - `Response` - A new response instance with default values.
26    #[inline(always)]
27    pub fn new() -> Self {
28        Self::default()
29    }
30
31    /// Tries to retrieve the value of a response header by its key.
32    ///
33    /// # Arguments
34    ///
35    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
36    ///
37    /// # Returns
38    ///
39    /// - `OptionResponseHeadersValue` - The optional header values.
40    #[inline(always)]
41    pub fn try_get_header<K>(&self, key: K) -> OptionResponseHeadersValue
42    where
43        K: AsRef<str>,
44    {
45        self.headers.get(key.as_ref()).cloned()
46    }
47
48    /// Retrieves the value of a response header by its key.
49    ///
50    /// # Arguments
51    ///
52    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
53    ///
54    /// # Returns
55    ///
56    /// - `ResponseHeadersValue` - The optional header values.
57    #[inline(always)]
58    pub fn get_header<K>(&self, key: K) -> ResponseHeadersValue
59    where
60        K: AsRef<str>,
61    {
62        self.try_get_header(key).unwrap()
63    }
64
65    /// Tries to retrieve the first value of a response header by its key.
66    ///
67    /// # Arguments
68    ///
69    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
70    ///
71    /// # Returns
72    ///
73    /// - `OptionResponseHeadersValueItem` - The first header value if exists.
74    #[inline(always)]
75    pub fn try_get_header_front<K>(&self, key: K) -> OptionResponseHeadersValueItem
76    where
77        K: AsRef<str>,
78    {
79        self.headers
80            .get(key.as_ref())
81            .and_then(|values| values.front().cloned())
82    }
83
84    /// Retrieves the first value of a response header by its key.
85    ///
86    /// # Arguments
87    ///
88    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
89    ///
90    /// # Returns
91    ///
92    /// - `ResponseHeadersValueItem` - The first header value if exists.
93    #[inline(always)]
94    pub fn get_header_front<K>(&self, key: K) -> ResponseHeadersValueItem
95    where
96        K: AsRef<str>,
97    {
98        self.try_get_header_front(key).unwrap()
99    }
100
101    /// Tries to retrieve the last value of a response header by its key.
102    ///
103    /// # Arguments
104    ///
105    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
106    ///
107    /// # Returns
108    ///
109    /// - `OptionResponseHeadersValueItem` - The last header value if exists.
110    #[inline(always)]
111    pub fn try_get_header_back<K>(&self, key: K) -> OptionResponseHeadersValueItem
112    where
113        K: AsRef<str>,
114    {
115        self.headers
116            .get(key.as_ref())
117            .and_then(|values| values.back().cloned())
118    }
119
120    /// Retrieves the last value of a response header by its key.
121    ///
122    /// # Arguments
123    ///
124    /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
125    ///
126    /// # Returns
127    ///
128    /// - `ResponseHeadersValueItem` - The last header value if exists.
129    #[inline(always)]
130    pub fn get_header_back<K>(&self, key: K) -> ResponseHeadersValueItem
131    where
132        K: AsRef<str>,
133    {
134        self.try_get_header_back(key).unwrap()
135    }
136
137    /// Checks if a header exists in the response.
138    ///
139    /// # Arguments
140    ///
141    /// - `AsRef<str>` - The header key to check (must implement AsRef<str>).
142    ///
143    /// # Returns
144    ///
145    /// - `bool` - Whether the header exists.
146    #[inline(always)]
147    pub fn has_header<K>(&self, key: K) -> bool
148    where
149        K: AsRef<str>,
150    {
151        let key: ResponseHeadersKey = key.as_ref().to_lowercase();
152        self.headers.contains_key(&key)
153    }
154
155    /// Checks if a header contains a specific value.
156    ///
157    /// # Arguments
158    ///
159    /// - `AsRef<str>` - The header key to check (must implement AsRef<str>).
160    /// - `AsRef<str>` - The value to search for (must implement AsRef<str>).
161    ///
162    /// # Returns
163    ///
164    /// - `bool` - Whether the header contains the value.
165    #[inline(always)]
166    pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
167    where
168        K: AsRef<str>,
169        V: AsRef<str>,
170    {
171        if let Some(values) = self.headers.get(key.as_ref()) {
172            values.contains(&value.as_ref().to_owned())
173        } else {
174            false
175        }
176    }
177
178    /// Gets the number of headers in the response.
179    ///
180    /// # Returns
181    ///
182    /// - `usize` - The count of unique header keys.
183    #[inline(always)]
184    pub fn get_headers_length(&self) -> usize {
185        self.headers.len()
186    }
187
188    /// Gets the number of values for a specific header key.
189    ///
190    /// # Arguments
191    ///
192    /// - `AsRef<str>` - The header key to count (must implement AsRef<str>).
193    ///
194    /// # Returns
195    ///
196    /// - `usize` - The count of values for the header.
197    #[inline(always)]
198    pub fn get_header_length<K>(&self, key: K) -> usize
199    where
200        K: AsRef<str>,
201    {
202        self.headers
203            .get(&key.as_ref().to_lowercase())
204            .map_or(0, |values| values.len())
205    }
206
207    /// Gets the total number of header values in the response.
208    ///
209    /// This counts all values across all headers, so a header with multiple values
210    /// will contribute more than one to the total count.
211    ///
212    /// # Returns
213    ///
214    /// - `usize` - The total count of all header values.
215    #[inline(always)]
216    pub fn get_headers_values_length(&self) -> usize {
217        self.headers.values().map(|values| values.len()).sum()
218    }
219
220    /// Retrieves the body content of the response as a UTF-8 encoded string.
221    ///
222    /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` as_ref a string.
223    /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character ().
224    ///
225    /// # Returns
226    ///
227    /// - `String` - The body content as a string.
228    #[inline(always)]
229    pub fn get_body_string(&self) -> String {
230        String::from_utf8_lossy(self.get_body()).into_owned()
231    }
232
233    /// Deserializes the body content of the response as_ref a specified type `T`.
234    ///
235    /// This method first retrieves the body content as a byte slice using `self.get_body()`.
236    /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
237    ///
238    /// # Arguments
239    ///
240    /// - `DeserializeOwned` - The target type to deserialize as_ref (must implement DeserializeOwned).
241    ///
242    /// # Returns
243    ///
244    /// - `ResultJsonError<T>` - The deserialization result.
245    pub fn get_body_json<T>(&self) -> ResultJsonError<T>
246    where
247        T: DeserializeOwned,
248    {
249        json_from_slice(self.get_body())
250    }
251
252    /// Determines whether the header should be skipped during setting.
253    ///
254    /// - Returns `true` if the header is empty or not allowed.
255    /// - Returns `false` if the header can be set.
256    #[inline(always)]
257    fn should_skip_header(&self, key: &ResponseHeadersKey) -> bool {
258        key.trim().is_empty() || key == CONTENT_LENGTH
259    }
260
261    /// Sets a header in the response, replacing any existing values.
262    ///
263    /// This function replaces all existing values for a header with a single new value.
264    ///
265    /// # Arguments
266    ///
267    /// - `AsRef<str>` - The header key (must implement AsRef<str>).
268    /// - `AsRef<str>` - The header value (must implement AsRef<String>).
269    ///
270    /// # Returns
271    ///
272    /// - `&mut Self` - A mutable reference to self for chaining.
273    #[inline(always)]
274    fn set_header_without_check<K, V>(&mut self, key: K, value: V) -> &mut Self
275    where
276        K: AsRef<str>,
277        V: AsRef<str>,
278    {
279        let key: ResponseHeadersKey = key.as_ref().to_lowercase();
280        let mut deque: VecDeque<String> = VecDeque::with_capacity(1);
281        deque.push_back(value.as_ref().to_owned());
282        self.headers.insert(key, deque);
283        self
284    }
285
286    /// Sets a header in the response, replacing any existing values.
287    ///
288    /// This function replaces all existing values for a header with a single new value.
289    ///
290    /// # Arguments
291    ///
292    /// - `AsRef<str>` - The header key (must implement AsRef<str>).
293    /// - `AsRef<str>` - The header value (must implement AsRef<String>).
294    ///
295    /// # Returns
296    ///
297    /// - `&mut Self` - A mutable reference to self for chaining.
298    #[inline(always)]
299    pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
300    where
301        K: AsRef<str>,
302        V: AsRef<str>,
303    {
304        let key: ResponseHeadersKey = key.as_ref().to_lowercase();
305        if self.should_skip_header(&key) {
306            return self;
307        }
308        let mut deque: VecDeque<String> = VecDeque::with_capacity(1);
309        deque.push_back(value.as_ref().to_owned());
310        self.headers.insert(key, deque);
311        self
312    }
313
314    /// Adds a header to the response.
315    ///
316    /// This function appends a value to the response headers.
317    /// If the header already exists, the new value will be added to the existing values.
318    ///
319    /// # Arguments
320    ///
321    /// - `AsRef<str>` - The header key (must implement AsRef<str>).
322    /// - `AsRef<str>` - The header value (must implement AsRef<String>).
323    ///
324    /// # Returns
325    ///
326    /// - `&mut Self` - A mutable reference to self for chaining.
327    #[inline(always)]
328    pub fn add_header<K, V>(&mut self, key: K, value: V) -> &mut Self
329    where
330        K: AsRef<str>,
331        V: AsRef<str>,
332    {
333        let key: ResponseHeadersKey = key.as_ref().to_lowercase();
334        if self.should_skip_header(&key) {
335            return self;
336        }
337        self.headers
338            .entry(key)
339            .or_default()
340            .push_back(value.as_ref().to_owned());
341        self
342    }
343
344    /// Removes a header from the response.
345    ///
346    /// This function removes all values for the specified header key.
347    ///
348    /// # Arguments
349    ///
350    /// - `AsRef<str>` - The header key to remove (must implement AsRef<str>).
351    ///
352    /// # Returns
353    ///
354    /// - `&mut Self` - A mutable reference to self for chaining.
355    #[inline(always)]
356    pub fn remove_header<K>(&mut self, key: K) -> &mut Self
357    where
358        K: AsRef<str>,
359    {
360        let _ = self.headers.remove(&key.as_ref().to_lowercase()).is_some();
361        self
362    }
363
364    /// Removes a specific value from a header in the response.
365    ///
366    /// This function removes only the specified value from the header.
367    /// If the header has multiple values, only the matching value is removed.
368    /// If this was the last value for the header, the entire header is removed.
369    ///
370    /// # Arguments
371    ///
372    /// - `AsRef<str>` - The header key (must implement AsRef<str>).
373    /// - `AsRef<str>` - The value to remove (must implement AsRef<String>).
374    ///
375    /// # Returns
376    ///
377    /// - `&mut Self` - A mutable reference to self for chaining.
378    #[inline(always)]
379    pub fn remove_header_value<K, V>(&mut self, key: K, value: V) -> &mut Self
380    where
381        K: AsRef<str>,
382        V: AsRef<str>,
383    {
384        let key: ResponseHeadersKey = key.as_ref().to_lowercase();
385        if let Some(values) = self.headers.get_mut(&key) {
386            values.retain(|v| v != &value.as_ref().to_owned());
387            if values.is_empty() {
388                self.headers.remove(&key);
389            }
390        }
391        self
392    }
393
394    /// Clears all headers from the response.
395    ///
396    /// This function removes all headers, leaving the headers map empty.
397    ///
398    /// # Returns
399    ///
400    /// - `&mut Self` - A mutable reference to self for chaining.
401    #[inline(always)]
402    pub fn clear_headers(&mut self) -> &mut Self {
403        self.headers.clear();
404        self
405    }
406
407    /// Sets the body of the response.
408    ///
409    /// This method allows you to set the body of the response by converting the provided
410    /// value as_ref a `ResponseBody` type. The `body` is updated with the converted value.
411    ///
412    /// # Arguments
413    ///
414    /// - `AsRef<[u8]>` - The body content (must implement AsRef<[u8]>).
415    ///
416    /// # Returns
417    ///
418    /// - `&mut Self` - A mutable reference to self for chaining.
419    #[inline(always)]
420    pub fn set_body<T>(&mut self, body: T) -> &mut Self
421    where
422        T: AsRef<[u8]>,
423    {
424        self.body = body.as_ref().to_owned();
425        self
426    }
427
428    /// Sets the reason phrase of the response.
429    ///
430    /// This method allows you to set the reason phrase of the response by converting the
431    /// provided value as_ref a `ResponseReasonPhrase` type. The `reason_phrase` is updated
432    /// with the converted value.
433    ///
434    /// # Arguments
435    ///
436    /// - `AsRef<str>` - The reason phrase (must implement AsRef<str>).
437    ///
438    /// # Returns
439    ///
440    /// - `&mut Self` - A mutable reference to self for chaining.
441    #[inline(always)]
442    pub fn set_reason_phrase<T>(&mut self, reason_phrase: T) -> &mut Self
443    where
444        T: AsRef<str>,
445    {
446        self.reason_phrase = reason_phrase.as_ref().to_owned();
447        self
448    }
449
450    /// Pushes a header with a key and value as_ref the response string.
451    ///
452    /// # Arguments
453    ///
454    /// - `&mut String`: A mutable reference to the string where the header will be added.
455    /// - `&str`: The header key as a string slice (`&str`).
456    /// - `&str`: The header value as a string slice (`&str`).
457    #[inline(always)]
458    fn push_header(response_string: &mut String, key: &str, value: &str) {
459        response_string.push_str(key);
460        response_string.push_str(COLON);
461        response_string.push_str(value);
462        response_string.push_str(HTTP_BR);
463    }
464
465    /// Pushes the first line of an HTTP response (version, status code, and reason phrase) as_ref the response string.
466    /// This corresponds to the status line of the HTTP response.
467    ///
468    /// # Arguments
469    ///
470    /// - `response_string`: A mutable reference to the string where the first line will be added.
471    #[inline(always)]
472    fn push_http_first_line(&self, response_string: &mut String) {
473        response_string.push_str(&self.get_version().to_string());
474        response_string.push_str(SPACE);
475        response_string.push_str(&self.get_status_code().to_string());
476        response_string.push_str(SPACE);
477        response_string.push_str(self.get_reason_phrase());
478        response_string.push_str(HTTP_BR);
479    }
480
481    /// Builds the full HTTP response as a byte vector.
482    ///
483    /// This method constructs the complete HTTP response, including the status line,
484    /// headers, and body. It handles content encoding, content type, connection
485    /// management, and content length.
486    ///
487    /// # Returns
488    ///
489    /// - `ResponseData` - The complete HTTP response bytes.
490    pub fn build(&mut self) -> ResponseData {
491        if self.reason_phrase.is_empty() {
492            self.set_reason_phrase(HttpStatus::phrase(*self.get_status_code()));
493        }
494        let mut response_string: String = String::with_capacity(DEFAULT_BUFFER_SIZE);
495        self.push_http_first_line(&mut response_string);
496        let compress_type_opt: OptionCompress = self
497            .try_get_header_back(CONTENT_ENCODING)
498            .map(|value| value.parse::<Compress>().unwrap_or_default());
499        if self.try_get_header_back(CONNECTION).is_none() {
500            self.set_header_without_check(CONNECTION, KEEP_ALIVE);
501        }
502        let content_type: ResponseHeadersValueItem =
503            self.try_get_header_back(CONTENT_TYPE).unwrap_or_else(|| {
504                let mut content_type: String = String::with_capacity(
505                    TEXT_HTML.len() + SEMICOLON_SPACE.len() + CHARSET_UTF_8.len(),
506                );
507                content_type.push_str(TEXT_HTML);
508                content_type.push_str(SEMICOLON_SPACE);
509                content_type.push_str(CHARSET_UTF_8);
510                self.set_header_without_check(CONTENT_TYPE, &content_type);
511                content_type
512            });
513        let mut body: ResponseBody = self.get_body().clone();
514        if let Some(compress_type) = compress_type_opt
515            && !compress_type.is_unknown()
516        {
517            body = compress_type
518                .encode(&body, DEFAULT_BUFFER_SIZE)
519                .into_owned();
520        }
521        if !content_type.eq_ignore_ascii_case(TEXT_EVENT_STREAM) {
522            self.set_header_without_check(CONTENT_LENGTH, body.len().to_string());
523        }
524        self.get_headers().iter().for_each(|(key, values)| {
525            for value in values.iter() {
526                Self::push_header(&mut response_string, key, value);
527            }
528        });
529        response_string.push_str(HTTP_BR);
530        let mut response_bytes: Vec<u8> = response_string.into_bytes();
531        response_bytes.extend_from_slice(&body);
532        response_bytes
533    }
534
535    /// Converts the response to a formatted string representation.
536    ///
537    /// This method provides a human-readable summary of the response, including its version,
538    /// status code, reason phrase, headers, and body information.
539    ///
540    /// # Returns
541    ///
542    /// A `String` containing formatted response details.
543    #[inline(always)]
544    pub fn get_string(&self) -> String {
545        let body: &Vec<u8> = self.get_body();
546        let body_type: &'static str = if std::str::from_utf8(body).is_ok() {
547            PLAIN
548        } else {
549            BINARY
550        };
551        format!(
552            "[Response] => [version]: {}; [status code]: {}; [reason]: {}; [headers]: {:?}; [body]: {} bytes {};",
553            self.get_version(),
554            self.get_status_code(),
555            self.get_reason_phrase(),
556            self.get_headers(),
557            body.len(),
558            body_type
559        )
560    }
561}