Skip to main content

http_type/response/
impl.rs

1use super::*;
2
3/// Implements the `std::error::Error` trait for `ResponseError`.
4/// This allows `ResponseError` to be treated as a standard Rust error type.
5impl Error for ResponseError {}
6
7/// Converts an I/O error to a `ResponseError`.
8///
9/// Maps I/O errors to `Send` variant with the error message.
10impl From<io::Error> for ResponseError {
11    /// Converts an I/O error to a `ResponseError`.
12    ///
13    /// # Arguments
14    ///
15    /// - `io::Error` - The I/O error to convert.
16    ///
17    /// # Returns
18    ///
19    /// - `ResponseError` - The corresponding response error as `Send`.
20    #[inline(always)]
21    fn from(error: io::Error) -> Self {
22        ResponseError::Send(error.to_string())
23    }
24}
25
26/// Implements the `Display` trait for `ResponseError`.
27/// This allows `ResponseError` variants to be formatted into human-readable strings.
28impl Display for ResponseError {
29    /// Formats the `ResponseError` variant into a human-readable string.
30    ///
31    /// # Arguments
32    ///
33    /// - `&mut Formatter<'_>` - The formatter used for writing the formatted string.
34    ///
35    /// # Returns
36    ///
37    /// A `fmt::Result` indicating whether the formatting was successful.
38    #[inline(always)]
39    fn fmt(&self, data: &mut Formatter<'_>) -> fmt::Result {
40        match self {
41            Self::NotFoundStream => {
42                write!(data, "Not found stream")
43            }
44            Self::ConnectionClosed => {
45                write!(data, "Connection has been closed")
46            }
47            Self::Terminated => {
48                write!(data, "Current processing has been terminated")
49            }
50            Self::Send(error) => write!(data, "Send error{COLON_SPACE}{error}"),
51            Self::FlushError(error) => write!(data, "Flush error{COLON_SPACE}{error}"),
52            Self::Unknown => write!(data, "Unknown error"),
53        }
54    }
55}
56
57/// Provides a default value for `Response`.
58///
59/// Returns a new `Response` instance with all fields initialized to their default values.
60impl Default for Response {
61    /// Builds the default `Response` with all fields set to their defaults.
62    #[inline(always)]
63    fn default() -> Self {
64        let http_status: HttpStatus = HttpStatus::default();
65        Self {
66            version: HttpVersion::Http1_1,
67            status_code: http_status.code(),
68            reason_phrase: http_status.to_string(),
69            headers: hash_map_xx_hash3_64(),
70            body: Vec::new(),
71        }
72    }
73}
74
75/// Inherent implementation of [`Response`].
76impl Response {
77    /// Pushes a header with a key and value as_ref the response string.
78    ///
79    /// # Arguments
80    ///
81    /// - `&mut String` - A mutable reference to the string where the header will be added.
82    /// - `&str` - The header key as a string slice (`&str`).
83    /// - `&str` - The header value as a string slice (`&str`).
84    #[inline(always)]
85    fn push_header(response_string: &mut String, key: &str, value: &str) {
86        response_string.push_str(key);
87        response_string.push_str(COLON);
88        response_string.push_str(value);
89        response_string.push_str(HTTP_BR);
90    }
91
92    /// Tries to retrieve the value of a response header by its key.
93    ///
94    /// # Arguments
95    ///
96    /// - `K` - The header's key, which must implement `AsRef<str>`.
97    ///
98    /// # Returns
99    ///
100    /// - `Option<ResponseHeadersValue>` - The optional header values.
101    #[inline(always)]
102    pub fn try_get_header<K>(&self, key: K) -> Option<ResponseHeadersValue>
103    where
104        K: AsRef<str>,
105    {
106        self.headers.get(key.as_ref()).cloned()
107    }
108
109    /// Retrieves the value of a response header by its key.
110    ///
111    /// # Arguments
112    ///
113    /// - `K` - The header's key, which must implement `AsRef<str>`.
114    ///
115    /// # Returns
116    ///
117    /// - `ResponseHeadersValue` - The optional header values.
118    ///
119    /// # Panics
120    ///
121    /// This function will panic if the header key is not found.
122    #[inline(always)]
123    pub fn get_header<K>(&self, key: K) -> ResponseHeadersValue
124    where
125        K: AsRef<str>,
126    {
127        self.try_get_header(key).unwrap()
128    }
129
130    /// Tries to retrieve the first value of a response header by its key.
131    ///
132    /// # Arguments
133    ///
134    /// - `K` - The header's key, which must implement `AsRef<str>`.
135    ///
136    /// # Returns
137    ///
138    /// - `Option<ResponseHeadersValueItem>` - The first header value if exists.
139    #[inline(always)]
140    pub fn try_get_header_front<K>(&self, key: K) -> Option<ResponseHeadersValueItem>
141    where
142        K: AsRef<str>,
143    {
144        self.headers
145            .get(key.as_ref())
146            .and_then(|data: &VecDeque<String>| data.front().cloned())
147    }
148
149    /// Retrieves the first value of a response header by its key.
150    ///
151    /// # Arguments
152    ///
153    /// - `K` - The header's key, which must implement `AsRef<str>`.
154    ///
155    /// # Returns
156    ///
157    /// - `ResponseHeadersValueItem` - The first header value if exists.
158    ///
159    /// # Panics
160    ///
161    /// This function will panic if the header key is not found.
162    #[inline(always)]
163    pub fn get_header_front<K>(&self, key: K) -> ResponseHeadersValueItem
164    where
165        K: AsRef<str>,
166    {
167        self.try_get_header_front(key).unwrap()
168    }
169
170    /// Tries to retrieve the last value of a response header by its key.
171    ///
172    /// # Arguments
173    ///
174    /// - `K` - The header's key, which must implement `AsRef<str>`.
175    ///
176    /// # Returns
177    ///
178    /// - `Option<ResponseHeadersValueItem>` - The last header value if exists.
179    #[inline(always)]
180    pub fn try_get_header_back<K>(&self, key: K) -> Option<ResponseHeadersValueItem>
181    where
182        K: AsRef<str>,
183    {
184        self.headers
185            .get(key.as_ref())
186            .and_then(|data: &VecDeque<String>| data.back().cloned())
187    }
188
189    /// Retrieves the last value of a response header by its key.
190    ///
191    /// # Arguments
192    ///
193    /// - `K` - The header's key, which must implement `AsRef<str>`.
194    ///
195    /// # Returns
196    ///
197    /// - `ResponseHeadersValueItem` - The last header value if exists.
198    ///
199    /// # Panics
200    ///
201    /// This function will panic if the header key is not found.
202    #[inline(always)]
203    pub fn get_header_back<K>(&self, key: K) -> ResponseHeadersValueItem
204    where
205        K: AsRef<str>,
206    {
207        self.try_get_header_back(key).unwrap()
208    }
209
210    /// Checks if a header exists in the response.
211    ///
212    /// # Arguments
213    ///
214    /// - `K` - The header key to check, which must implement `AsRef<str>`.
215    ///
216    /// # Returns
217    ///
218    /// - `bool` - Whether the header exists.
219    #[inline(always)]
220    pub fn has_header<K>(&self, key: K) -> bool
221    where
222        K: AsRef<str>,
223    {
224        self.get_headers().contains_key(key.as_ref())
225    }
226
227    /// Checks if a header contains a specific value.
228    ///
229    /// # Arguments
230    ///
231    /// - `K` - The header key to check, which must implement `AsRef<str>`.
232    /// - `V` - The value to search for, which must implement `AsRef<str>`.
233    ///
234    /// # Returns
235    ///
236    /// - `bool` - Whether the header contains the value.
237    #[inline(always)]
238    pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
239    where
240        K: AsRef<str>,
241        V: AsRef<str>,
242    {
243        if let Some(values) = self.get_headers().get(key.as_ref()) {
244            values.contains(&value.as_ref().to_owned())
245        } else {
246            false
247        }
248    }
249
250    /// Gets the number of headers in the response.
251    ///
252    /// # Returns
253    ///
254    /// - `usize` - The count of unique header keys.
255    #[inline(always)]
256    pub fn get_headers_size(&self) -> usize {
257        self.headers.len()
258    }
259
260    /// Tries to get the number of values for a specific header key.
261    ///
262    /// # Arguments
263    ///
264    /// - `K` - The header key to count, which must implement `AsRef<str>`.
265    ///
266    /// # Returns
267    ///
268    /// - `Option<usize>` - The count of values for the header.
269    #[inline(always)]
270    pub fn try_get_header_size<K>(&self, key: K) -> Option<usize>
271    where
272        K: AsRef<str>,
273    {
274        self.headers
275            .get(key.as_ref())
276            .map(|data: &VecDeque<String>| data.len())
277    }
278
279    /// Gets the number of values for a specific header key.
280    ///
281    /// # Arguments
282    ///
283    /// - `K` - The header key to count, which must implement `AsRef<str>`.
284    ///
285    /// # Returns
286    ///
287    /// - `usize` - The count of values for the header.
288    ///
289    /// # Panics
290    ///
291    /// This function will panic if the header key is not found.
292    #[inline(always)]
293    pub fn get_header_size<K>(&self, key: K) -> usize
294    where
295        K: AsRef<str>,
296    {
297        self.try_get_header_size(key).unwrap()
298    }
299
300    /// Gets the total number of header values in the response.
301    ///
302    /// This counts all values across all headers, so a header with multiple values
303    /// will contribute more than one to the total count.
304    ///
305    /// # Returns
306    ///
307    /// - `usize` - The total count of all header values.
308    #[inline(always)]
309    pub fn get_headers_values_size(&self) -> usize {
310        self.headers
311            .values()
312            .map(|data: &VecDeque<String>| data.len())
313            .sum()
314    }
315
316    /// Retrieves the body content of the response as a UTF-8 encoded string.
317    ///
318    /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` as_ref a string.
319    /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character ().
320    ///
321    /// # Returns
322    ///
323    /// - `String` - The body content as a string.
324    #[inline(always)]
325    pub fn get_body_string(&self) -> String {
326        String::from_utf8_lossy(self.get_body()).into_owned()
327    }
328
329    /// Deserializes the body content of the response as_ref a specified type `T`.
330    ///
331    /// This method first retrieves the body content as a byte slice using `self.get_body()`.
332    /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
333    ///
334    /// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
335    ///
336    /// # Returns
337    ///
338    /// - `Result<T, serde_json::Error>` - The deserialization result.
339    pub fn try_get_body_json<T>(&self) -> Result<T, serde_json::Error>
340    where
341        T: DeserializeOwned,
342    {
343        serde_json::from_slice(self.get_body())
344    }
345
346    /// Deserializes the body content of the response as_ref a specified type `T`.
347    ///
348    /// This method first retrieves the body content as a byte slice using `self.get_body()`.
349    /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
350    ///
351    /// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
352    ///
353    /// # Returns
354    ///
355    /// - `T` - The deserialized body content.
356    ///
357    /// # Panics
358    ///
359    /// This function will panic if the deserialization fails.
360    pub fn get_body_json<T>(&self) -> T
361    where
362        T: DeserializeOwned,
363    {
364        self.try_get_body_json().unwrap()
365    }
366
367    /// Determines whether the header should be skipped during setting.
368    ///
369    /// # Arguments
370    ///
371    /// - `&str` - The header key to inspect.
372    ///
373    /// # Returns
374    ///
375    /// - `bool` - `true` if the header is empty or not allowed, `false` if the header can be set.
376    #[inline(always)]
377    fn should_skip_header(&self, key: &str) -> bool {
378        key.trim().is_empty() || key == CONTENT_LENGTH
379    }
380
381    /// Sets a header in the response, replacing any existing values.
382    ///
383    /// This function replaces all existing values for a header with a single new value.
384    ///
385    /// # Arguments
386    ///
387    /// - `K` - The header key, which must implement `AsRef<str>`.
388    /// - `V` - The header value, which must implement `AsRef<String>`.
389    ///
390    /// # Returns
391    ///
392    /// - `&mut Self` - A mutable reference to self for chaining.
393    #[inline(always)]
394    fn set_header_without_check<K, V>(&mut self, key: K, value: V) -> &mut Self
395    where
396        K: AsRef<str>,
397        V: AsRef<str>,
398    {
399        let key: &str = key.as_ref();
400        let value: &str = value.as_ref();
401        if let Some(values) = self.get_mut_headers().get_mut(key) {
402            values.truncate(1);
403            if let Some(slot) = values.front_mut() {
404                slot.clear();
405                slot.push_str(value);
406            } else {
407                values.push_back(value.to_owned());
408            }
409            return self;
410        }
411        // A recycled entry carries the buffers of the name and of the value,
412        // so a response that sets the same headers over and over stops
413        // allocating for them.
414        let (mut name, mut values): (String, VecDeque<String>) =
415            take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
416        name.clear();
417        name.push_str(key);
418        // A recycled entry may carry the values of a header that was sent
419        // more than once. Those values belong to that header, so only the
420        // first one is kept and the rest are dropped.
421        while values.len() > 1 {
422            values.pop_back();
423        }
424        if values.is_empty() {
425            values.push_back(String::new());
426        }
427        if let Some(slot) = values.front_mut() {
428            slot.clear();
429            slot.push_str(value.as_ref());
430        }
431        self.get_mut_headers().insert(name, values);
432        self
433    }
434
435    /// Sets a header in the response, replacing any existing values.
436    ///
437    /// This function replaces all existing values for a header with a single new value.
438    ///
439    /// # Arguments
440    ///
441    /// - `K` - The header key, which must implement `AsRef<str>`.
442    /// - `V` - The header value, which must implement `AsRef<String>`.
443    ///
444    /// # Returns
445    ///
446    /// - `&mut Self` - A mutable reference to self for chaining.
447    #[inline(always)]
448    pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
449    where
450        K: AsRef<str>,
451        V: AsRef<str>,
452    {
453        let key: &str = key.as_ref();
454        if self.should_skip_header(key) {
455            return self;
456        }
457        self.set_header_without_check(key, value)
458    }
459
460    /// Adds a header to the response.
461    ///
462    /// This function appends a value to the response headers.
463    /// If the header already exists, the new value will be added to the existing values.
464    ///
465    /// # Arguments
466    ///
467    /// - `K` - The header key, which must implement `AsRef<str>`.
468    /// - `V` - The header value, which must implement `AsRef<String>`.
469    ///
470    /// # Returns
471    ///
472    /// - `&mut Self` - A mutable reference to self for chaining.
473    #[inline(always)]
474    pub fn add_header<K, V>(&mut self, key: K, value: V) -> &mut Self
475    where
476        K: AsRef<str>,
477        V: AsRef<str>,
478    {
479        let key: ResponseHeadersKey = key.as_ref().to_owned();
480        if self.should_skip_header(&key) {
481            return self;
482        }
483        self.get_mut_headers()
484            .entry(key)
485            .or_default()
486            .push_back(value.as_ref().to_owned());
487        self
488    }
489
490    /// Removes a header from the response.
491    ///
492    /// This function removes all values for the specified header key.
493    ///
494    /// # Arguments
495    ///
496    /// - `K` - The header key to remove, which must implement `AsRef<str>`.
497    ///
498    /// # Returns
499    ///
500    /// - `&mut Self` - A mutable reference to self for chaining.
501    #[inline(always)]
502    pub fn remove_header<K>(&mut self, key: K) -> &mut Self
503    where
504        K: AsRef<str>,
505    {
506        let _: bool = self.get_mut_headers().remove(key.as_ref()).is_some();
507        self
508    }
509
510    /// Removes a specific value from a header in the response.
511    ///
512    /// This function removes only the specified value from the header.
513    /// If the header has multiple values, only the matching value is removed.
514    /// If this was the last value for the header, the entire header is removed.
515    ///
516    /// # Arguments
517    ///
518    /// - `K` - The header key, which must implement `AsRef<str>`.
519    /// - `V` - The value to remove, which must implement `AsRef<String>`.
520    ///
521    /// # Returns
522    ///
523    /// - `&mut Self` - A mutable reference to self for chaining.
524    #[inline(always)]
525    pub fn remove_header_value<K, V>(&mut self, key: K, value: V) -> &mut Self
526    where
527        K: AsRef<str>,
528        V: AsRef<str>,
529    {
530        let key: ResponseHeadersKey = key.as_ref().to_owned();
531        if let Some(values) = self.get_mut_headers().get_mut(&key) {
532            values.retain(|data: &String| data != &value.as_ref().to_owned());
533            if values.is_empty() {
534                self.get_mut_headers().remove(&key);
535            }
536        }
537        self
538    }
539
540    /// Clears all headers from the response.
541    ///
542    /// This function removes all headers, leaving the headers map empty.
543    ///
544    /// # Returns
545    ///
546    /// - `&mut Self` - A mutable reference to self for chaining.
547    #[inline(always)]
548    pub fn clear_headers(&mut self) -> &mut Self {
549        self.get_mut_headers().clear();
550        self
551    }
552
553    /// Resets the response to its default state while retaining allocated capacity.
554    ///
555    /// This keeps the header map and body allocations so persistent
556    /// (keep-alive) connections avoid repeated allocation per request.
557    ///
558    /// # Returns
559    ///
560    /// - `&mut Self` - A mutable reference to self for chaining.
561    pub fn reset(&mut self) -> &mut Self {
562        let http_status: HttpStatus = HttpStatus::default();
563        self.set_status_code(http_status.code());
564        self.get_mut_reason_phrase().clear();
565        let _: fmt::Result = write!(self.get_mut_reason_phrase(), "{}", http_status);
566        self.recycle_headers();
567        self.get_mut_body().clear();
568        self
569    }
570
571    /// Hands the header entries to the pool and empties the header map.
572    ///
573    /// The map ends up empty, exactly as clearing it would, but the name and
574    /// the value buffers of every header survive in the pool. The next
575    /// response reuses them instead of allocating new ones.
576    ///
577    /// # Returns
578    ///
579    /// - `()` - The headers have been recycled.
580    fn recycle_headers(&mut self) {
581        let headers: &mut ResponseHeaders = self.get_mut_headers();
582        if headers.is_empty() {
583            return;
584        }
585        for (key, values) in headers.drain() {
586            return_header_entry((key, values));
587        }
588    }
589
590    /// Tries to parse cookies from the `Set-Cookie` header.
591    ///
592    /// This method retrieves the last `Set-Cookie` header value and parses it
593    /// into a collection of key-value pairs representing the cookies.
594    ///
595    /// # Returns
596    ///
597    /// - `Option<Cookies>` - The parsed cookies if the `Set-Cookie` header exists, otherwise `None`.
598    #[inline(always)]
599    pub fn try_get_cookies(&self) -> Option<Cookies> {
600        self.try_get_header_back(SET_COOKIE)
601            .map(|cookie_header: String| Cookie::parse(cookie_header))
602    }
603
604    /// Parses cookies from the `Set-Cookie` headers.
605    ///
606    /// This method retrieves all `Set-Cookie` header values and parses each one
607    /// into a collection of key-value pairs representing the cookies.
608    ///
609    /// # Returns
610    ///
611    /// - `Cookies` - The parsed cookies.
612    ///
613    /// # Panics
614    ///
615    /// This function will panic if the `Set-Cookie` header is not found.
616    #[inline(always)]
617    pub fn get_cookies(&self) -> Cookies {
618        self.try_get_cookies().unwrap()
619    }
620
621    /// Tries to get a cookie value by its key from `Set-Cookie` headers.
622    ///
623    /// This method parses the cookies from all `Set-Cookie` headers,
624    /// then attempts to retrieve the value for the specified key.
625    ///
626    /// # Arguments
627    ///
628    /// - `K` - The cookie key, which implements `AsRef<str>`.
629    ///
630    /// # Returns
631    ///
632    /// - `Option<CookieValue>` - The cookie value if exists.
633    #[inline(always)]
634    pub fn try_get_cookie<K>(&self, key: K) -> Option<CookieValue>
635    where
636        K: AsRef<str>,
637    {
638        self.try_get_cookies()
639            .and_then(|cookies: Cookies| cookies.get(key.as_ref()).cloned())
640    }
641
642    /// Gets a cookie value by its key from `Set-Cookie` headers.
643    ///
644    /// This method parses the cookies from all `Set-Cookie` headers,
645    /// then retrieves the value for the specified key.
646    ///
647    /// # Arguments
648    ///
649    /// - `K` - The cookie key, which implements `AsRef<str>`.
650    ///
651    /// # Returns
652    ///
653    /// - `CookieValue` - The cookie value.
654    ///
655    /// # Panics
656    ///
657    /// This function will panic if the `Set-Cookie` header is not found
658    /// or the cookie key does not exist.
659    #[inline(always)]
660    pub fn get_cookie<K>(&self, key: K) -> CookieValue
661    where
662        K: AsRef<str>,
663    {
664        self.try_get_cookie(key).unwrap()
665    }
666
667    /// Builds the full HTTP response as a byte vector.
668    ///
669    /// This method constructs the complete HTTP response, including the status line,
670    /// headers, and body. It handles content encoding, content type, connection
671    /// management, and content length.
672    ///
673    /// # Returns
674    ///
675    /// - `ResponseData` - The complete HTTP response bytes.
676    pub fn build(&mut self) -> ResponseData {
677        if self.get_reason_phrase().is_empty() || self.get_reason_phrase().as_str() == OK {
678            self.set_reason_phrase(HttpStatus::phrase(self.get_status_code()));
679        }
680        let compress_type_opt: Option<Compress> = self
681            .get_headers()
682            .get(CONTENT_ENCODING)
683            .and_then(|values: &VecDeque<String>| values.back())
684            .map(|data: &String| data.parse::<Compress>().unwrap_or_default());
685        if self
686            .get_headers()
687            .get(CONNECTION)
688            .and_then(|values: &VecDeque<String>| values.back())
689            .is_none()
690        {
691            self.set_header_without_check(CONNECTION, KEEP_ALIVE);
692        }
693        if self
694            .get_headers()
695            .get(CONTENT_TYPE)
696            .and_then(|values: &VecDeque<String>| values.back())
697            .is_none()
698        {
699            self.set_header_without_check(CONTENT_TYPE, default_content_type());
700        }
701        let is_event_stream: bool = self
702            .get_headers()
703            .get(CONTENT_TYPE)
704            .and_then(|values: &VecDeque<String>| values.back())
705            .is_some_and(|value: &String| value.eq_ignore_ascii_case(TEXT_EVENT_STREAM));
706        let compressed_body: Option<Vec<u8>> = match compress_type_opt {
707            Some(compress_type) if !compress_type.is_unknown() => Some(
708                compress_type
709                    .encode(self.get_body(), DEFAULT_BUFFER_SIZE)
710                    .into_owned(),
711            ),
712            _ => None,
713        };
714        let body_len: usize = compressed_body
715            .as_ref()
716            .map_or_else(|| self.get_body().len(), Vec::len);
717        if !is_event_stream {
718            // The length is written into a pooled string, so announcing it
719            // does not allocate a fresh one for every response.
720            let mut length: String = take_recycled_string().unwrap_or_default();
721            length.clear();
722            let _: fmt::Result = write!(length, "{body_len}");
723            self.set_header_without_check(CONTENT_LENGTH, length.as_str());
724            return_recycled_string(length);
725        }
726        let mut head_size: usize = self.get_reason_phrase().len() + B_16 + HTTP_BR.len();
727        head_size += self
728            .get_headers()
729            .iter()
730            .map(|header_entry: (&String, &VecDeque<String>)| {
731                let (header_key, header_values): (&String, &VecDeque<String>) = header_entry;
732                header_values
733                    .iter()
734                    .map(|header_value: &String| {
735                        header_key.len() + COLON.len() + header_value.len() + HTTP_BR.len()
736                    })
737                    .sum::<usize>()
738            })
739            .sum::<usize>();
740        let mut response_string: String = String::with_capacity(head_size + body_len);
741        let _: fmt::Result = write!(
742            response_string,
743            "{} {} {}{HTTP_BR}",
744            self.get_version(),
745            self.get_status_code(),
746            self.get_reason_phrase()
747        );
748        self.get_headers()
749            .iter()
750            .for_each(|header_entry: (&String, &VecDeque<String>)| {
751                let (header_key, header_values): (&String, &VecDeque<String>) = header_entry;
752                for header_value in header_values.iter() {
753                    Self::push_header(&mut response_string, header_key, header_value);
754                }
755            });
756        response_string.push_str(HTTP_BR);
757        let mut response_bytes: Vec<u8> = response_string.into_bytes();
758        match &compressed_body {
759            Some(body) => response_bytes.extend_from_slice(body),
760            None => response_bytes.extend_from_slice(self.get_body()),
761        }
762        response_bytes
763    }
764}