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