Skip to main content

rust_web_server/response/
mod.rs

1#[cfg(test)]
2mod tests;
3#[cfg(test)]
4mod example;
5
6use std::io;
7use std::io::{BufRead, Cursor, Read};
8use crate::body::multipart_form_data::FormMultipartData;
9use crate::core::New;
10use crate::header::Header;
11use crate::ext::string_ext::StringExt;
12use crate::http::{HTTP, VERSION};
13use crate::mime_type::MimeType;
14use crate::range::{ContentRange, Range};
15use crate::request::{METHOD, Request};
16use crate::symbol::SYMBOL;
17
18#[derive(PartialEq, Eq, Clone, Debug)]
19pub struct Error {
20    pub status_code_reason_phrase: &'static StatusCodeReasonPhrase,
21    pub message: String,
22}
23
24/// An HTTP response. Build one inside [`Controller::process`] and return it.
25///
26/// Set `status_code` and `reason_phrase` from [`STATUS_CODE_REASON_PHRASE`],
27/// push body content via [`Range::get_content_range`] into `content_range_list`,
28/// and add any extra headers to `headers`.
29///
30/// For large files, set `stream_file` to the absolute file path instead of loading
31/// the body into `content_range_list`. The server will stream it with
32/// `Transfer-Encoding: chunked` so memory usage stays constant regardless of file size.
33///
34/// For proxy passthrough (SSE, AI token streams, large downloads), set `stream_pipe`
35/// to a boxed `Read` source instead. The server streams its output with
36/// `Transfer-Encoding: chunked` immediately after sending the response headers.
37pub struct Response {
38    /// HTTP version string, e.g. `"HTTP/1.1"`.
39    pub http_version: String,
40    /// Numeric status code, e.g. `200`. Set from [`STATUS_CODE_REASON_PHRASE`].
41    pub status_code: i16,
42    /// Reason phrase, e.g. `"OK"`. Set from [`STATUS_CODE_REASON_PHRASE`].
43    pub reason_phrase: String,
44    /// Response headers. Pre-populated with standard headers by [`Header::get_header_list`].
45    pub headers: Vec<Header>,
46    /// Response body as a list of content ranges (supports multipart and range responses).
47    pub content_range_list: Vec<ContentRange>,
48    /// If set, the server streams this file with `Transfer-Encoding: chunked`
49    /// instead of using `content_range_list`. Use for files larger than ~8 MB.
50    pub stream_file: Option<String>,
51    /// If set, the server pipes bytes from this reader with `Transfer-Encoding: chunked`
52    /// immediately after sending the response headers. Takes precedence over
53    /// `content_range_list` and `stream_file`. The reader is consumed and not cloned.
54    pub stream_pipe: Option<Box<dyn std::io::Read + Send>>,
55}
56
57impl Clone for Response {
58    fn clone(&self) -> Self {
59        Response {
60            http_version: self.http_version.clone(),
61            status_code: self.status_code,
62            reason_phrase: self.reason_phrase.clone(),
63            headers: self.headers.clone(),
64            content_range_list: self.content_range_list.clone(),
65            stream_file: self.stream_file.clone(),
66            stream_pipe: None,
67        }
68    }
69}
70
71impl PartialEq for Response {
72    fn eq(&self, other: &Self) -> bool {
73        self.http_version == other.http_version
74            && self.status_code == other.status_code
75            && self.reason_phrase == other.reason_phrase
76            && self.headers == other.headers
77            && self.content_range_list == other.content_range_list
78            && self.stream_file == other.stream_file
79    }
80}
81
82impl Eq for Response {}
83
84impl std::fmt::Debug for Response {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        f.debug_struct("Response")
87            .field("http_version", &self.http_version)
88            .field("status_code", &self.status_code)
89            .field("reason_phrase", &self.reason_phrase)
90            .field("headers", &self.headers)
91            .field("content_range_list", &self.content_range_list)
92            .field("stream_file", &self.stream_file)
93            .field("stream_pipe", &self.stream_pipe.as_ref().map(|_| "<stream>"))
94            .finish()
95    }
96}
97
98#[derive(PartialEq, Eq, Clone, Debug)]
99pub struct StatusCodeReasonPhrase {
100    pub status_code: &'static i16,
101    pub reason_phrase: &'static str,
102}
103
104#[derive(PartialEq, Eq, Clone, Debug)]
105pub struct ResponseStatusCodeReasonPhrase {
106    pub n100_continue: &'static StatusCodeReasonPhrase,
107    pub n101_switching_protocols: &'static StatusCodeReasonPhrase,
108    pub n102_processing: &'static StatusCodeReasonPhrase,
109    pub n103_early_hints: &'static StatusCodeReasonPhrase,
110    pub n200_ok: &'static StatusCodeReasonPhrase,
111    pub n201_created: &'static StatusCodeReasonPhrase,
112    pub n202_accepted: &'static StatusCodeReasonPhrase,
113    pub n203_non_authoritative_information: &'static StatusCodeReasonPhrase,
114    pub n204_no_content: &'static StatusCodeReasonPhrase,
115    pub n205_reset_content: &'static StatusCodeReasonPhrase,
116    pub n206_partial_content: &'static StatusCodeReasonPhrase,
117    pub n207_multi_status: &'static StatusCodeReasonPhrase,
118    pub n208_already_reported: &'static StatusCodeReasonPhrase,
119    pub n226_im_used: &'static StatusCodeReasonPhrase,
120    pub n300_multiple_choices: &'static StatusCodeReasonPhrase,
121    pub n301_moved_permanently: &'static StatusCodeReasonPhrase,
122    pub n302_found: &'static StatusCodeReasonPhrase,
123    pub n303_see_other: &'static StatusCodeReasonPhrase,
124    pub n304_not_modified: &'static StatusCodeReasonPhrase,
125    pub n307_temporary_redirect: &'static StatusCodeReasonPhrase,
126    pub n308_permanent_redirect: &'static StatusCodeReasonPhrase,
127    pub n400_bad_request: &'static StatusCodeReasonPhrase,
128    pub n401_unauthorized: &'static StatusCodeReasonPhrase,
129    pub n402_payment_required: &'static StatusCodeReasonPhrase,
130    pub n403_forbidden: &'static StatusCodeReasonPhrase,
131    pub n404_not_found: &'static StatusCodeReasonPhrase,
132    pub n405_method_not_allowed: &'static StatusCodeReasonPhrase,
133    pub n406_not_acceptable: &'static StatusCodeReasonPhrase,
134    pub n407_proxy_authentication_required: &'static StatusCodeReasonPhrase,
135    pub n408_request_timeout: &'static StatusCodeReasonPhrase,
136    pub n409_conflict: &'static StatusCodeReasonPhrase,
137    pub n410_gone: &'static StatusCodeReasonPhrase,
138    pub n411_length_required: &'static StatusCodeReasonPhrase,
139    pub n412_precondition_failed: &'static StatusCodeReasonPhrase,
140    pub n413_payload_too_large: &'static StatusCodeReasonPhrase,
141    pub n414_uri_too_long: &'static StatusCodeReasonPhrase,
142    pub n415_unsupported_media_type: &'static StatusCodeReasonPhrase,
143    pub n416_range_not_satisfiable: &'static StatusCodeReasonPhrase,
144    pub n417_expectation_failed: &'static StatusCodeReasonPhrase,
145    pub n418_im_a_teapot: &'static StatusCodeReasonPhrase,
146    pub n421_misdirected_request: &'static StatusCodeReasonPhrase,
147    pub n422_unprocessable_entity: &'static StatusCodeReasonPhrase,
148    pub n423_locked: &'static StatusCodeReasonPhrase,
149    pub n424_failed_dependency: &'static StatusCodeReasonPhrase,
150    pub n425_too_early: &'static StatusCodeReasonPhrase,
151    pub n426_upgrade_required: &'static StatusCodeReasonPhrase,
152    pub n428_precondition_required: &'static StatusCodeReasonPhrase,
153    pub n429_too_many_requests: &'static StatusCodeReasonPhrase,
154    pub n431_request_header_fields_too_large: &'static StatusCodeReasonPhrase,
155    pub n451_unavailable_for_legal_reasons: &'static StatusCodeReasonPhrase,
156    pub n500_internal_server_error: &'static StatusCodeReasonPhrase,
157    pub n501_not_implemented: &'static StatusCodeReasonPhrase,
158    pub n502_bad_gateway: &'static StatusCodeReasonPhrase,
159    pub n503_service_unavailable: &'static StatusCodeReasonPhrase,
160    pub n504_gateway_timeout: &'static StatusCodeReasonPhrase,
161    pub n505_http_version_not_supported: &'static StatusCodeReasonPhrase,
162    pub n506_variant_also_negotiates: &'static StatusCodeReasonPhrase,
163    pub n507_insufficient_storage: &'static StatusCodeReasonPhrase,
164    pub n508_loop_detected: &'static StatusCodeReasonPhrase,
165    pub n510_not_extended: &'static StatusCodeReasonPhrase,
166    pub n511_network_authentication_required: &'static StatusCodeReasonPhrase,
167}
168
169pub const STATUS_CODE_REASON_PHRASE: ResponseStatusCodeReasonPhrase = ResponseStatusCodeReasonPhrase {
170    n100_continue: &StatusCodeReasonPhrase { status_code: &100, reason_phrase: "Continue" },
171    n101_switching_protocols: &StatusCodeReasonPhrase { status_code: &101, reason_phrase: "Switching Protocols" },
172    n102_processing: &StatusCodeReasonPhrase { status_code: &102, reason_phrase: "Processing" },
173    n103_early_hints: &StatusCodeReasonPhrase { status_code: &103, reason_phrase: "Early Hints" },
174    n200_ok: &StatusCodeReasonPhrase {
175        status_code: &200,
176        reason_phrase: "OK"
177    },
178
179    n201_created: &StatusCodeReasonPhrase { status_code: &201, reason_phrase: "Created" },
180    n202_accepted: &StatusCodeReasonPhrase { status_code: &202, reason_phrase: "Accepted" },
181    n203_non_authoritative_information: &StatusCodeReasonPhrase { status_code: &203, reason_phrase: "Non Authoritative Information" },
182    n204_no_content: &StatusCodeReasonPhrase {
183        status_code: &204,
184        reason_phrase: "No Content"
185    },
186
187    n205_reset_content: &StatusCodeReasonPhrase { status_code: &205, reason_phrase: "Reset Content" },
188    n206_partial_content: &StatusCodeReasonPhrase {
189        status_code: &206,
190        reason_phrase: "Partial Content"
191    },
192
193    n207_multi_status: &StatusCodeReasonPhrase { status_code: &207, reason_phrase: "Multi-Status" },
194    n208_already_reported: &StatusCodeReasonPhrase { status_code: &208, reason_phrase: "Already Reported" },
195    n226_im_used: &StatusCodeReasonPhrase { status_code: &226, reason_phrase: "IM Used" },
196    n300_multiple_choices: &StatusCodeReasonPhrase { status_code: &300, reason_phrase: "Multiple Choices" },
197    n301_moved_permanently: &StatusCodeReasonPhrase { status_code: &301, reason_phrase: "Moved Permanently" },
198    n302_found: &StatusCodeReasonPhrase { status_code: &302, reason_phrase: "Found" },
199    n303_see_other: &StatusCodeReasonPhrase { status_code: &303, reason_phrase: "See Other" },
200    n304_not_modified: &StatusCodeReasonPhrase { status_code: &304, reason_phrase: "Not Modified" },
201    n307_temporary_redirect: &StatusCodeReasonPhrase { status_code: &307, reason_phrase: "Temporary Redirect" },
202    n308_permanent_redirect: &StatusCodeReasonPhrase { status_code: &308, reason_phrase: "Permanent Redirect" },
203    n400_bad_request: &StatusCodeReasonPhrase {
204        status_code: &400,
205        reason_phrase: "Bad Request"
206    },
207
208    n401_unauthorized: &StatusCodeReasonPhrase { status_code: &401, reason_phrase: "Unauthorized" },
209    n402_payment_required: &StatusCodeReasonPhrase { status_code: &402, reason_phrase: "Payment Required" },
210    n403_forbidden: &StatusCodeReasonPhrase { status_code: &403, reason_phrase: "Forbidden" },
211    n404_not_found: &StatusCodeReasonPhrase {
212        status_code: &404,
213        reason_phrase: "Not Found"
214    },
215
216    n405_method_not_allowed: &StatusCodeReasonPhrase { status_code: &405, reason_phrase: "Method Not Allowed" },
217    n406_not_acceptable: &StatusCodeReasonPhrase { status_code: &406, reason_phrase: "Not Acceptable" },
218    n407_proxy_authentication_required: &StatusCodeReasonPhrase { status_code: &407, reason_phrase: "Proxy Authentication Required" },
219    n408_request_timeout: &StatusCodeReasonPhrase { status_code: &408, reason_phrase: "Request Timeout" },
220    n409_conflict: &StatusCodeReasonPhrase { status_code: &409, reason_phrase: "Conflict" },
221    n410_gone: &StatusCodeReasonPhrase { status_code: &410, reason_phrase: "Gone" },
222    n411_length_required: &StatusCodeReasonPhrase { status_code: &411, reason_phrase: "Length Required" },
223    n412_precondition_failed: &StatusCodeReasonPhrase { status_code: &412, reason_phrase: "Precondition Failed" },
224    n413_payload_too_large: &StatusCodeReasonPhrase { status_code: &413, reason_phrase: "Payload Too Large" },
225    n414_uri_too_long: &StatusCodeReasonPhrase { status_code: &414, reason_phrase: "URI Too Long" },
226    n415_unsupported_media_type: &StatusCodeReasonPhrase { status_code: &415, reason_phrase: "Unsupported Media Type" },
227    n416_range_not_satisfiable: &StatusCodeReasonPhrase {
228        status_code: &416,
229        reason_phrase: "Range Not Satisfiable"
230    },
231
232    n417_expectation_failed: &StatusCodeReasonPhrase { status_code: &417, reason_phrase: "Expectation Failed" },
233    n418_im_a_teapot: &StatusCodeReasonPhrase { status_code: &418, reason_phrase: "I'm A Teapot" },
234    n421_misdirected_request: &StatusCodeReasonPhrase { status_code: &421, reason_phrase: "Misdirected Request" },
235    n422_unprocessable_entity: &StatusCodeReasonPhrase { status_code: &422, reason_phrase: "Unprocessable Entity" },
236    n423_locked: &StatusCodeReasonPhrase { status_code: &423, reason_phrase: "Locked" },
237    n424_failed_dependency: &StatusCodeReasonPhrase { status_code: &424, reason_phrase: "Failed Dependency" },
238    n425_too_early: &StatusCodeReasonPhrase { status_code: &425, reason_phrase: "Too Early" },
239    n426_upgrade_required: &StatusCodeReasonPhrase { status_code: &426, reason_phrase: "Upgrade Required" },
240    n428_precondition_required: &StatusCodeReasonPhrase { status_code: &428, reason_phrase: "Precondition Required" },
241    n429_too_many_requests: &StatusCodeReasonPhrase { status_code: &429, reason_phrase: "Too Many Requests" },
242    n431_request_header_fields_too_large: &StatusCodeReasonPhrase { status_code: &431, reason_phrase: "Request Header Fields Too Large" },
243    n451_unavailable_for_legal_reasons: &StatusCodeReasonPhrase { status_code: &451, reason_phrase: "Unavailable For Legal Reasons" },
244    n500_internal_server_error: &StatusCodeReasonPhrase {
245        status_code: &500,
246        reason_phrase: "Internal Server Error"
247    },
248    n501_not_implemented: &StatusCodeReasonPhrase { status_code: &501, reason_phrase: "Not Implemented" },
249    n502_bad_gateway: &StatusCodeReasonPhrase { status_code: &502, reason_phrase: "Bad Gateway" },
250    n503_service_unavailable: &StatusCodeReasonPhrase { status_code: &503, reason_phrase: "Service Unavailable" },
251    n504_gateway_timeout: &StatusCodeReasonPhrase { status_code: &504, reason_phrase: "Gateway Timeout" },
252    n505_http_version_not_supported: &StatusCodeReasonPhrase { status_code: &505, reason_phrase: "HTTP Version Not Supported" },
253    n506_variant_also_negotiates: &StatusCodeReasonPhrase { status_code: &506, reason_phrase: "Variant Also Negotiates" },
254    n507_insufficient_storage: &StatusCodeReasonPhrase { status_code: &507, reason_phrase: "Insufficient Storage" },
255    n508_loop_detected: &StatusCodeReasonPhrase { status_code: &508, reason_phrase: "Loop Detected" },
256    n510_not_extended: &StatusCodeReasonPhrase { status_code: &510, reason_phrase: "Not Extended" },
257    n511_network_authentication_required: &StatusCodeReasonPhrase { status_code: &511, reason_phrase: "Network Authentication Required" }
258};
259
260/// The `Content-Range` value for a single-part body, or `None` when the
261/// response shouldn't carry one. RFC 9110 §14.4 gives `Content-Range` meaning
262/// only on `206 Partial Content` (and `416`, which rws answers with a plain
263/// error body), so full `200` responses get no such header. `range.end` is
264/// inclusive.
265pub fn content_range_header_value(status_code: i16, content_range: &ContentRange) -> Option<String> {
266    if status_code != *STATUS_CODE_REASON_PHRASE.n206_partial_content.status_code {
267        return None;
268    }
269    Some(format!(
270        "{} {}-{}/{}",
271        Range::BYTES, content_range.range.start, content_range.range.end, content_range.size
272    ))
273}
274
275impl Response {
276
277    pub fn build(status: StatusCodeReasonPhrase, header_list : Vec<Header>, body: Vec<ContentRange>) -> Response {
278        Response {
279            http_version: VERSION.http_1_1.to_string(),
280            status_code: *status.status_code,
281            reason_phrase: status.reason_phrase.to_string(),
282            headers: header_list,
283            content_range_list: body,
284            stream_file: None,
285            stream_pipe: None,
286        }
287    }
288
289    pub fn status_code_reason_phrase_list() -> Vec<&'static StatusCodeReasonPhrase> {
290        let list = vec![
291            STATUS_CODE_REASON_PHRASE.n100_continue,
292            STATUS_CODE_REASON_PHRASE.n101_switching_protocols,
293            STATUS_CODE_REASON_PHRASE.n102_processing,
294            STATUS_CODE_REASON_PHRASE.n103_early_hints,
295            STATUS_CODE_REASON_PHRASE.n200_ok,
296            STATUS_CODE_REASON_PHRASE.n201_created,
297            STATUS_CODE_REASON_PHRASE.n202_accepted,
298            STATUS_CODE_REASON_PHRASE.n203_non_authoritative_information,
299            STATUS_CODE_REASON_PHRASE.n204_no_content,
300            STATUS_CODE_REASON_PHRASE.n205_reset_content,
301            STATUS_CODE_REASON_PHRASE.n206_partial_content,
302            STATUS_CODE_REASON_PHRASE.n207_multi_status,
303            STATUS_CODE_REASON_PHRASE.n208_already_reported,
304            STATUS_CODE_REASON_PHRASE.n226_im_used,
305            STATUS_CODE_REASON_PHRASE.n300_multiple_choices,
306            STATUS_CODE_REASON_PHRASE.n301_moved_permanently,
307            STATUS_CODE_REASON_PHRASE.n302_found,
308            STATUS_CODE_REASON_PHRASE.n303_see_other,
309            STATUS_CODE_REASON_PHRASE.n304_not_modified,
310            STATUS_CODE_REASON_PHRASE.n307_temporary_redirect,
311            STATUS_CODE_REASON_PHRASE.n308_permanent_redirect,
312            STATUS_CODE_REASON_PHRASE.n400_bad_request,
313            STATUS_CODE_REASON_PHRASE.n401_unauthorized,
314            STATUS_CODE_REASON_PHRASE.n402_payment_required,
315            STATUS_CODE_REASON_PHRASE.n403_forbidden,
316            STATUS_CODE_REASON_PHRASE.n404_not_found,
317            STATUS_CODE_REASON_PHRASE.n405_method_not_allowed,
318            STATUS_CODE_REASON_PHRASE.n406_not_acceptable,
319            STATUS_CODE_REASON_PHRASE.n407_proxy_authentication_required,
320            STATUS_CODE_REASON_PHRASE.n408_request_timeout,
321            STATUS_CODE_REASON_PHRASE.n409_conflict,
322            STATUS_CODE_REASON_PHRASE.n410_gone,
323            STATUS_CODE_REASON_PHRASE.n411_length_required,
324            STATUS_CODE_REASON_PHRASE.n412_precondition_failed,
325            STATUS_CODE_REASON_PHRASE.n413_payload_too_large,
326            STATUS_CODE_REASON_PHRASE.n414_uri_too_long,
327            STATUS_CODE_REASON_PHRASE.n415_unsupported_media_type,
328            STATUS_CODE_REASON_PHRASE.n416_range_not_satisfiable,
329            STATUS_CODE_REASON_PHRASE.n417_expectation_failed,
330            STATUS_CODE_REASON_PHRASE.n418_im_a_teapot,
331            STATUS_CODE_REASON_PHRASE.n421_misdirected_request,
332            STATUS_CODE_REASON_PHRASE.n422_unprocessable_entity,
333            STATUS_CODE_REASON_PHRASE.n423_locked,
334            STATUS_CODE_REASON_PHRASE.n424_failed_dependency,
335            STATUS_CODE_REASON_PHRASE.n425_too_early,
336            STATUS_CODE_REASON_PHRASE.n426_upgrade_required,
337            STATUS_CODE_REASON_PHRASE.n428_precondition_required,
338            STATUS_CODE_REASON_PHRASE.n429_too_many_requests,
339            STATUS_CODE_REASON_PHRASE.n431_request_header_fields_too_large,
340            STATUS_CODE_REASON_PHRASE.n451_unavailable_for_legal_reasons,
341            STATUS_CODE_REASON_PHRASE.n500_internal_server_error,
342            STATUS_CODE_REASON_PHRASE.n501_not_implemented,
343            STATUS_CODE_REASON_PHRASE.n502_bad_gateway,
344            STATUS_CODE_REASON_PHRASE.n503_service_unavailable,
345            STATUS_CODE_REASON_PHRASE.n504_gateway_timeout,
346            STATUS_CODE_REASON_PHRASE.n505_http_version_not_supported,
347            STATUS_CODE_REASON_PHRASE.n506_variant_also_negotiates,
348            STATUS_CODE_REASON_PHRASE.n507_insufficient_storage,
349            STATUS_CODE_REASON_PHRASE.n508_loop_detected,
350            STATUS_CODE_REASON_PHRASE.n510_not_extended,
351            STATUS_CODE_REASON_PHRASE.n511_network_authentication_required,
352        ];
353        list
354    }
355
356    pub const _ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE: &'static str = "Unable to parse status code";
357
358    pub const _HTTP_VERSION_AND_STATUS_CODE_AND_REASON_PHRASE_REGEX: &'static str = "(?P<http_version>\\w+/\\w+.\\w)\\s(?P<status_code>\\w+)\\s(?P<reason_phrase>.+)";
359
360    pub fn _get_header(&self, name: String) -> Option<&Header> {
361        // Header names are case-insensitive (RFC 9110 §5.1), as in Request::get_header.
362        let header =  self.headers.iter().find(|x| x.name.eq_ignore_ascii_case(&name));
363        header
364    }
365
366    pub fn generate_body(content_range_list: Vec<ContentRange>) -> Vec<u8> {
367        let mut body = vec![];
368        let one = 1;
369
370        if content_range_list.len() == one {
371            // Move the body out rather than copy it: for a large file that
372            // copy was a second full-size buffer per in-flight response.
373            let mut content_range_list = content_range_list;
374            return content_range_list.swap_remove(0).body;
375        }
376
377        if content_range_list.len() > one {
378            for (i, content_range) in content_range_list.iter().enumerate() {
379                let mut body_str = SYMBOL.empty_string.to_string();
380                if i != 0 {
381                    body_str.push_str(SYMBOL.new_line_carriage_return);
382                }
383                body_str.push_str(SYMBOL.hyphen);
384                body_str.push_str(SYMBOL.hyphen);
385                body_str.push_str(Range::STRING_SEPARATOR);
386                body_str.push_str(SYMBOL.new_line_carriage_return);
387                let content_type = [Header::_CONTENT_TYPE, Header::NAME_VALUE_SEPARATOR, SYMBOL.whitespace, &content_range.content_type.to_string()].join("");
388                body_str.push_str(content_type.as_str());
389                body_str.push_str(SYMBOL.new_line_carriage_return);
390                let content_range_header = [Header::_CONTENT_RANGE, Header::NAME_VALUE_SEPARATOR, SYMBOL.whitespace, Range::BYTES, SYMBOL.whitespace, &content_range.range.start.to_string(), SYMBOL.hyphen, &content_range.range.end.to_string(), SYMBOL.slash, &content_range.size].join("");
391                body_str.push_str(content_range_header.as_str());
392                body_str.push_str(SYMBOL.new_line_carriage_return);
393                body_str.push_str(SYMBOL.new_line_carriage_return);
394
395                let inner_body = [body_str.as_bytes(), &content_range.body].concat();
396                body = [body, inner_body].concat();
397            }
398            let mut trailing_separator = SYMBOL.empty_string.to_string();
399            trailing_separator.push_str(SYMBOL.new_line_carriage_return);
400            trailing_separator.push_str(SYMBOL.hyphen);
401            trailing_separator.push_str(SYMBOL.hyphen);
402            trailing_separator.push_str(Range::STRING_SEPARATOR);
403            body = [&body, trailing_separator.as_bytes()].concat();
404        }
405
406        body
407    }
408
409    /// The serialized response: status line + headers, then the body.
410    pub fn generate_response(response: Response, request: Request) -> Vec<u8> {
411        let (mut head, body) = Response::generate_response_parts(response, request);
412        head.extend_from_slice(&body);
413        head
414    }
415
416    /// Like [`generate_response`](Self::generate_response), but returns the
417    /// head (status line + headers + blank line) and the body separately, so
418    /// a connection writer can send them back to back without first copying
419    /// a large body into one combined buffer. The body is empty for HEAD and
420    /// OPTIONS.
421    pub fn generate_response_parts(mut response: Response, request: Request) -> (Vec<u8>, Vec<u8>) {
422
423        if response.content_range_list.len() == 1 {
424            let content_range_index = 0;
425            let content_range = response.content_range_list.get(content_range_index).unwrap();
426            response.headers.push(Header {
427                name: Header::_CONTENT_TYPE.to_string(),
428                value: content_range.content_type.to_string()
429            });
430
431            if let Some(value) = content_range_header_value(response.status_code, content_range) {
432                response.headers.push(Header {
433                    name: Header::_CONTENT_RANGE.to_string(),
434                    value,
435                });
436            }
437
438            response.headers.push(Header {
439                name: Header::_CONTENT_LENGTH.to_string(),
440                value: content_range.body.len().to_string()
441            });
442        }
443
444        if response.content_range_list.len() > 1 {
445            let content_range_header_value = [
446                Range::MULTIPART,
447                SYMBOL.slash,
448                Range::BYTERANGES,
449                SYMBOL.semicolon,
450                SYMBOL.whitespace,
451                Range::BOUNDARY,
452                SYMBOL.equals,
453                Range::STRING_SEPARATOR
454            ].join("");
455            response.headers.push(Header {
456                name: Header::_CONTENT_TYPE.to_string(),
457                value: content_range_header_value,
458            });
459        }
460
461        let body = Response::generate_body(response.content_range_list);
462
463        // One buffer, sized up front, written once: this used to build a
464        // String per header, grow a second one, join the status line and
465        // copy it all again with format! — the biggest allocation cost of a
466        // small response.
467        let status_code = response.status_code.to_string();
468        let capacity = response.http_version.len() + status_code.len() + response.reason_phrase.len() + 4
469            + response.headers.iter().map(|h| h.name.len() + h.value.len() + 4).sum::<usize>()
470            + 2;
471        let mut head = Vec::with_capacity(capacity);
472        head.extend_from_slice(response.http_version.as_bytes());
473        head.push(b' ');
474        head.extend_from_slice(status_code.as_bytes());
475        head.push(b' ');
476        head.extend_from_slice(response.reason_phrase.as_bytes());
477        head.extend_from_slice(b"\r\n");
478        for header in &response.headers {
479            head.extend_from_slice(header.name.as_bytes());
480            head.extend_from_slice(Header::NAME_VALUE_SEPARATOR.as_bytes());
481            head.extend_from_slice(header.value.as_bytes());
482            head.extend_from_slice(b"\r\n");
483        }
484        head.extend_from_slice(b"\r\n");
485
486        let is_head = request.method == METHOD.head;
487        let is_options = request.method == METHOD.options;
488
489        if is_head || is_options {
490            (head, Vec::new())
491        } else {
492            (head, body)
493        }
494    }
495
496    pub fn _parse_response(response_vec_u8: &[u8]) -> Response {
497        let mut cursor = io::Cursor::new(response_vec_u8);
498
499        let mut response = Response {
500            http_version: "".to_string(),
501            status_code: 0,
502            reason_phrase: "".to_string(),
503            headers: vec![],
504            content_range_list: vec![],
505            stream_file: None,
506            stream_pipe: None,
507        };
508
509        let content_length: usize = 0;
510        let iteration_number : usize = 0;
511
512        Response::_parse_raw_response_via_cursor(&mut cursor, iteration_number, &mut response, content_length);
513
514        return response;
515    }
516
517    pub fn _parse_http_version_status_code_reason_phrase_string(http_version_status_code_reason_phrase: &str) -> Result<(String, i16, String), String> {
518        let truncated = StringExt::truncate_new_line_carriage_return(http_version_status_code_reason_phrase);
519
520        let boxed_split = truncated.split_once(SYMBOL.whitespace);
521        if boxed_split.is_none() {
522            return Err(Response::_ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE.to_string())
523        }
524
525        let (http_version, status_code_reason_phrase) = boxed_split.unwrap();
526        if !HTTP::is_supported_version(http_version) {
527            return Err(Response::_ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE.to_string())
528        }
529
530        // RFC 9112 §4: status-line = HTTP-version SP status-code SP [ reason-phrase ].
531        // The reason phrase is optional free text that clients should ignore
532        // (Python's http.server sends "404 File not found"), and any 3-digit
533        // code is valid — so neither is checked against the known list.
534        let (status_code, reason_phrase) = status_code_reason_phrase
535            .split_once(SYMBOL.whitespace)
536            .unwrap_or((status_code_reason_phrase, ""));
537
538        let is_three_digits = status_code.len() == 3 && status_code.bytes().all(|b| b.is_ascii_digit());
539        let status_code_i16 = match status_code.parse::<i16>() {
540            Ok(code) if is_three_digits && code >= 100 => code,
541            _ => return Err(Response::_ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE.to_string()),
542        };
543
544        return Ok((http_version.to_string(), status_code_i16, reason_phrase.to_string()))
545    }
546
547    pub fn _parse_http_response_header_string(header_string: &str) -> Header {
548        // A line without ": " (malformed upstream input) is a name with an
549        // empty value, as in Request::parse_http_request_header_string —
550        // not an index-out-of-bounds panic.
551        let (header_name, raw_header_value) = header_string
552            .split_once(Header::NAME_VALUE_SEPARATOR)
553            .unwrap_or((header_string, ""));
554        let header_value = StringExt::truncate_new_line_carriage_return(raw_header_value);
555
556
557        Header {
558            name: header_name.to_string(),
559            value: header_value.to_string()
560        }
561    }
562
563    pub fn _parse_raw_response_via_cursor(
564        cursor: &mut Cursor<&[u8]>,
565        mut iteration_number: usize,
566        response: &mut Response,
567        mut content_length: usize) {
568
569        let mut buffer = vec![];
570        let boxed_read = cursor.read_until(b'\n', &mut buffer);
571        if boxed_read.is_err() {
572            eprintln!("unable to parse raw response via cursor {}", boxed_read.err().unwrap());
573            return;
574        }
575        let bytes_offset = boxed_read.unwrap();
576        let mut buffer_as_u8_array: &[u8] = &buffer;
577        let string = String::from_utf8(Vec::from(buffer_as_u8_array)).unwrap();
578
579        let is_first_iteration = iteration_number == 0;
580        let new_line_char_found = bytes_offset != 0;
581        let current_string_is_empty = string.trim().len() == 0;
582
583        if is_first_iteration {
584            let boxed_http_version_status_code_reason_phrase = Response::_parse_http_version_status_code_reason_phrase_string(&string);
585            if boxed_http_version_status_code_reason_phrase.is_err() {
586                let error = boxed_http_version_status_code_reason_phrase.err().unwrap();
587                eprintln!("{}", error);
588                return;
589            }
590
591            let (http_version, status_code, reason_phrase) = boxed_http_version_status_code_reason_phrase.unwrap();
592
593            response.http_version = http_version;
594            response.status_code = status_code;
595            response.reason_phrase = reason_phrase;
596        }
597
598        if current_string_is_empty {
599            let content_type = response._get_header(Header::_CONTENT_TYPE.to_string()).unwrap();
600            let is_multipart = Response::_is_multipart_byteranges_content_type(&content_type);
601
602            if is_multipart {
603                let content_range_list : Vec<ContentRange> = vec![];
604
605                let mut buf = vec![];
606                cursor.read_until(b'\n', &mut buf).unwrap();
607                let boxed_value = Range::_parse_multipart_body(cursor, content_range_list);
608                let mut range_list = vec![];
609                if boxed_value.is_ok() {
610                    range_list = boxed_value.unwrap();
611                }
612                response.content_range_list = range_list;
613            } else {
614                buffer = vec![];
615                let boxed_read = cursor.read_to_end(&mut buffer);
616                if boxed_read.is_ok() {
617                    buffer_as_u8_array = &buffer;
618
619                    let content_range = ContentRange {
620                        unit: Range::BYTES.to_string(),
621                        range: Range {
622                            start: 0,
623                            end: buffer_as_u8_array.len() as u64
624                        },
625                        size: buffer_as_u8_array.len().to_string(),
626                        body: Vec::from(buffer_as_u8_array),
627                        content_type: content_type.value.to_string()
628                    };
629                    response.content_range_list = vec![content_range];
630                } else {
631                    let reason = boxed_read.err().unwrap();
632                    eprintln!("error reading file: {}", reason.to_string())
633                }
634
635            }
636
637            return;
638        }
639
640        if new_line_char_found && !current_string_is_empty {
641            let mut header = Header { name: "".to_string(), value: "".to_string() };
642            if !is_first_iteration {
643                header = Response::_parse_http_response_header_string(&string);
644                if header.name.eq_ignore_ascii_case(Header::_CONTENT_LENGTH) {
645                    // No error channel here: treat an invalid value as absent.
646                    content_length = header.value.trim().parse().unwrap_or(0);
647                }
648            }
649
650            response.headers.push(header);
651            iteration_number += 1;
652            Response::_parse_raw_response_via_cursor(cursor, iteration_number, response, content_length);
653        }
654    }
655
656    pub fn _is_multipart_byteranges_content_type(content_type: &Header) -> bool {
657        let multipart_byteranges =
658            [
659                Range::MULTIPART,
660                SYMBOL.slash,
661                Range::BYTERANGES
662            ].join("");
663        let is_multipart_byteranges = content_type.value.starts_with(&multipart_byteranges);
664        is_multipart_byteranges
665    }
666
667
668    pub fn get_response(
669        status_code_reason_phrase: &StatusCodeReasonPhrase,
670        boxed_header_list: Option<Vec<Header>>,
671        boxed_content_range_list: Option<Vec<ContentRange>>) -> Response {
672
673        let mut header_list: Vec<Header> = vec![];
674        if boxed_header_list.is_some() {
675            header_list = boxed_header_list.unwrap();
676        }
677
678        let mut content_range_list: Vec<ContentRange> = vec![];
679        if boxed_content_range_list.is_some() {
680            content_range_list = boxed_content_range_list.unwrap();
681        }
682
683        let response = Response {
684            http_version: VERSION.http_1_1.to_string(),
685            status_code: *status_code_reason_phrase.status_code,
686            reason_phrase: status_code_reason_phrase.reason_phrase.to_string(),
687            headers: header_list,
688            content_range_list,
689            stream_file: None,
690            stream_pipe: None,
691        };
692
693        response
694    }
695
696    /// Build a `Content-Type: application/json` response from already-serialized bytes.
697    ///
698    /// Takes raw bytes rather than a `Serialize` value so it carries no dependency on the
699    /// `serde` feature — pair it with `serde_json::to_vec` (or hand-rolled JSON) to build `body`.
700    /// For a one-line serialize-and-respond helper on a typed value, see [`crate::json::Json`]
701    /// (`serde` feature).
702    ///
703    /// ```rust,no_run
704    /// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
705    ///
706    /// let response = Response::json(STATUS_CODE_REASON_PHRASE.n200_ok, br#"{"ok":true}"#.to_vec());
707    /// ```
708    pub fn json(status_code_reason_phrase: &StatusCodeReasonPhrase, body: Vec<u8>) -> Response {
709        let content_range = Range::get_content_range(body, MimeType::APPLICATION_JSON.to_string());
710        Response::get_response(status_code_reason_phrase, None, Some(vec![content_range]))
711    }
712
713    /// Build a `Content-Type: text/plain` response from a body string.
714    ///
715    /// ```rust,no_run
716    /// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
717    ///
718    /// let response = Response::text(STATUS_CODE_REASON_PHRASE.n400_bad_request, "invalid input");
719    /// ```
720    pub fn text(status_code_reason_phrase: &StatusCodeReasonPhrase, body: &str) -> Response {
721        let content_range = Range::get_content_range(body.as_bytes().to_vec(), MimeType::TEXT_PLAIN.to_string());
722        Response::get_response(status_code_reason_phrase, None, Some(vec![content_range]))
723    }
724
725    pub fn generate(&mut self) -> Vec<u8> {
726        let response = &mut self.clone();
727
728        if response.content_range_list.len() == 1 {
729            let content_range_index = 0;
730            let content_range = response.content_range_list.get(content_range_index).unwrap();
731            response.headers.push(Header {
732                name: Header::_CONTENT_TYPE.to_string(),
733                value: content_range.content_type.to_string()
734            });
735
736            if let Some(value) = content_range_header_value(response.status_code, content_range) {
737                response.headers.push(Header {
738                    name: Header::_CONTENT_RANGE.to_string(),
739                    value,
740                });
741            }
742
743            response.headers.push(Header {
744                name: Header::_CONTENT_LENGTH.to_string(),
745                value: content_range.body.len().to_string()
746            });
747        }
748
749        if response.content_range_list.len() > 1 {
750            let content_range_header_value = [
751                Range::MULTIPART,
752                SYMBOL.slash,
753                Range::BYTERANGES,
754                SYMBOL.semicolon,
755                SYMBOL.whitespace,
756                Range::BOUNDARY,
757                SYMBOL.equals,
758                Range::STRING_SEPARATOR
759            ].join("");
760            response.headers.push(Header {
761                name: Header::_CONTENT_TYPE.to_string(),
762                value: content_range_header_value,
763            });
764        }
765
766        let response_clone = response.clone();
767        let body = Response::generate_body(response_clone.content_range_list);
768
769        let mut headers_str = SYMBOL.new_line_carriage_return.to_string();
770
771        let header_list = response.headers.clone();
772        for header in header_list {
773            let mut header_string = SYMBOL.empty_string.to_string();
774            header_string.push_str(&header.name);
775            header_string.push_str(Header::NAME_VALUE_SEPARATOR);
776            header_string.push_str(&header.value);
777            header_string.push_str(SYMBOL.new_line_carriage_return);
778            headers_str.push_str(&header_string);
779        }
780
781        let response_clone = response.clone();
782        let status = [response_clone.http_version, response.status_code.to_string(), response_clone.reason_phrase].join(SYMBOL.whitespace);
783        let response_without_body = format!(
784            "{}{}{}",
785            status,
786            headers_str,
787            SYMBOL.new_line_carriage_return,
788        );
789
790
791        [response_without_body.into_bytes(), body].concat()
792    }
793
794    pub fn get_header(&self, name: String) -> Option<&Header> {
795        self._get_header(name)
796    }
797
798    pub fn parse(response_vec_u8: &[u8]) -> Result<Response, String> {
799        let total_bytes : i32 = response_vec_u8.len() as i32;
800        let bytes_read = 0;
801        let mut cursor = io::Cursor::new(response_vec_u8);
802
803        let mut response = Response {
804            http_version: "".to_string(),
805            status_code: 0,
806            reason_phrase: "".to_string(),
807            headers: vec![],
808            content_range_list: vec![],
809            stream_file: None,
810            stream_pipe: None,
811        };
812
813        let content_length: usize = 0;
814        let iteration_number : usize = 0;
815
816        let boxed_parse = Response::parse_raw_response_via_cursor(
817            &mut cursor, iteration_number,
818            &mut response,
819            content_length,
820            total_bytes,
821            bytes_read
822        );
823        if boxed_parse.is_err() {
824            let message = boxed_parse.err().unwrap();
825            return Err(message);
826        }
827
828        return Ok(response);
829    }
830
831    pub fn parse_raw_response_via_cursor(
832        cursor: &mut Cursor<&[u8]>,
833        mut iteration_number: usize,
834        response: &mut Response,
835        _content_length: usize,
836        total_bytes: i32,
837        mut bytes_read: i32) -> Result<(), String> {
838        // A loop, not tail recursion (which Rust doesn't guarantee to
839        // eliminate): one stack frame per header line let a backend sending
840        // thousands of header lines overflow the stack and abort the process.
841        loop {
842
843            let mut buffer = vec![];
844            let boxed_read = cursor.read_until(b'\n', &mut buffer);
845            if boxed_read.is_err() {
846                let message = format!("unable to parse raw response via cursor {}", boxed_read.err().unwrap());
847                return Err(message);
848            }
849            let bytes_offset = boxed_read.unwrap();
850            bytes_read = bytes_read + bytes_offset as i32;
851            if bytes_read == total_bytes {
852                // end of stream
853            }
854            let mut buffer_as_u8_array: &[u8] = &buffer;
855            let boxed_string = String::from_utf8(Vec::from(buffer_as_u8_array));
856            if boxed_string.is_err() {
857                let message = boxed_string.err().unwrap().to_string();
858                return Err(message);
859            }
860            let string = boxed_string.unwrap();
861
862            let is_first_iteration = iteration_number == 0;
863            let new_line_char_found = bytes_offset != 0;
864            let current_string_is_empty = string.trim().len() == 0;
865
866            if is_first_iteration {
867                let boxed_http_version_status_code_reason_phrase = Response::_parse_http_version_status_code_reason_phrase_string(&string);
868                if boxed_http_version_status_code_reason_phrase.is_err() {
869                    let message = boxed_http_version_status_code_reason_phrase.err().unwrap();
870                    return Err(message);
871                }
872
873                let (http_version, status_code, reason_phrase) = boxed_http_version_status_code_reason_phrase.unwrap();
874
875                response.http_version = http_version;
876                response.status_code = status_code;
877                response.reason_phrase = reason_phrase;
878            }
879
880            if current_string_is_empty {
881                let mut is_multipart = false;
882                // if response does not contain Content-Type, it will be defaulted to APPLICATION_OCTET_STREAM
883                let mut content_type = MimeType::APPLICATION_OCTET_STREAM;
884
885                let boxed_content_type = response.get_header(Header::_CONTENT_TYPE.to_string());
886                if boxed_content_type.is_some() {
887                    let content_type_header = response.get_header(Header::_CONTENT_TYPE.to_string()).unwrap();
888                    content_type = content_type_header.value.as_str();
889                    is_multipart = Response::_is_multipart_byteranges_content_type(&content_type_header);
890                }
891
892
893                if is_multipart {
894                    let content_range_list : Vec<ContentRange> = vec![];
895                    let boxed_content_type = response.get_header(Header::_CONTENT_TYPE.to_string());
896                    if boxed_content_type.is_none() {
897                        return Err("Content-Type is missing".to_string());
898                    }
899                    let content_type = boxed_content_type.unwrap();
900                    let boxed_boundary = FormMultipartData::extract_boundary(content_type.value.as_str());
901                    if boxed_boundary.is_err() {
902                        return Err("unable to extract boundary from Content-Type".to_string());
903                    }
904                    let boundary = boxed_boundary.unwrap();
905
906                    let is_opening_boundary_read = false;
907                    let boxed_content_range_list =
908                        Range::parse_multipart_body_with_boundary(
909                            cursor,
910                            content_range_list,
911                            boundary,
912                            total_bytes,
913                            bytes_read,
914                            is_opening_boundary_read);
915                    if boxed_content_range_list.is_err() {
916                        let message = boxed_content_range_list.err().unwrap();
917                        return Err(message);
918                    }
919
920                    response.content_range_list = boxed_content_range_list.unwrap();
921                } else {
922                    buffer = vec![];
923                    let boxed_read = cursor.read_to_end(&mut buffer);
924                    if boxed_read.is_err() {
925                        let message = boxed_read.err().unwrap().to_string();
926                        return Err(message);
927                    }
928                    let bytes_offset = boxed_read.unwrap();
929                    bytes_read = bytes_read + bytes_offset as i32;
930                    if bytes_read == total_bytes {
931                        // end of stream
932                    }
933
934                    buffer_as_u8_array = &buffer;
935
936                    let content_range = ContentRange {
937                        unit: Range::BYTES.to_string(),
938                        range: Range {
939                            start: 0,
940                            end: buffer_as_u8_array.len() as u64
941                        },
942                        size: buffer_as_u8_array.len().to_string(),
943                        body: Vec::from(buffer_as_u8_array),
944                        content_type: content_type.to_string()
945                    };
946                    response.content_range_list = vec![content_range];
947
948
949                }
950
951                return Ok(());
952            }
953
954            if new_line_char_found && !current_string_is_empty {
955                if !is_first_iteration {
956                    let boxed_header = Response::parse_http_response_header_string(&string);
957                    if boxed_header.is_err() {
958                        let message = boxed_header.err().unwrap();
959                        return Err(message);
960                    }
961                    let header = boxed_header.unwrap();
962                    if header.name.eq_ignore_ascii_case(Header::_CONTENT_LENGTH) {
963                        // An upstream-supplied value: reject garbage instead of panicking.
964                        let _: usize = header.value.trim().parse()
965                            .map_err(|_| format!("invalid Content-Length: {:?}", header.value))?;
966                    }
967                    response.headers.push(header);
968                }
969
970            iteration_number += 1;
971        } else {
972            return Err("unable to parse".to_string());
973        }
974        }
975    }
976
977    pub fn parse_http_response_header_string(header_string: &str) -> Result<Header, String> {
978        let header_parts: Option<(&str, &str)> = header_string.split_once(Header::NAME_VALUE_SEPARATOR);
979        if header_parts.is_none() {
980            let message = format!("unable to parse header: {}", header_string);
981            return Err(message);
982        }
983        let (header_name, raw_header_value) = header_parts.unwrap();
984        let header_value = StringExt::truncate_new_line_carriage_return(&raw_header_value);
985
986        Ok(Header {
987            name: header_name.to_string(),
988            value: header_value.to_string()
989        })
990    }
991}
992
993impl New for Response {
994    fn new() -> Self {
995        Response {
996            http_version: VERSION.http_1_1.to_string(),
997            status_code: *STATUS_CODE_REASON_PHRASE.n501_not_implemented.status_code,
998            reason_phrase: STATUS_CODE_REASON_PHRASE.n501_not_implemented.reason_phrase.to_string(),
999            headers: vec![],
1000            content_range_list: vec![],
1001            stream_file: None,
1002            stream_pipe: None,
1003        }
1004    }
1005}