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