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            let index = 0;
372            let content_range = content_range_list.get(index).unwrap();
373            body = content_range.body.to_vec();
374        }
375
376        if content_range_list.len() > one {
377            for (i, content_range) in content_range_list.iter().enumerate() {
378                let mut body_str = SYMBOL.empty_string.to_string();
379                if i != 0 {
380                    body_str.push_str(SYMBOL.new_line_carriage_return);
381                }
382                body_str.push_str(SYMBOL.hyphen);
383                body_str.push_str(SYMBOL.hyphen);
384                body_str.push_str(Range::STRING_SEPARATOR);
385                body_str.push_str(SYMBOL.new_line_carriage_return);
386                let content_type = [Header::_CONTENT_TYPE, Header::NAME_VALUE_SEPARATOR, SYMBOL.whitespace, &content_range.content_type.to_string()].join("");
387                body_str.push_str(content_type.as_str());
388                body_str.push_str(SYMBOL.new_line_carriage_return);
389                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("");
390                body_str.push_str(content_range_header.as_str());
391                body_str.push_str(SYMBOL.new_line_carriage_return);
392                body_str.push_str(SYMBOL.new_line_carriage_return);
393
394                let inner_body = [body_str.as_bytes(), &content_range.body].concat();
395                body = [body, inner_body].concat();
396            }
397            let mut trailing_separator = SYMBOL.empty_string.to_string();
398            trailing_separator.push_str(SYMBOL.new_line_carriage_return);
399            trailing_separator.push_str(SYMBOL.hyphen);
400            trailing_separator.push_str(SYMBOL.hyphen);
401            trailing_separator.push_str(Range::STRING_SEPARATOR);
402            body = [&body, trailing_separator.as_bytes()].concat();
403        }
404
405        body
406    }
407
408    pub fn generate_response(mut response: Response, request: Request) -> Vec<u8> {
409
410        if response.content_range_list.len() == 1 {
411            let content_range_index = 0;
412            let content_range = response.content_range_list.get(content_range_index).unwrap();
413            response.headers.push(Header {
414                name: Header::_CONTENT_TYPE.to_string(),
415                value: content_range.content_type.to_string()
416            });
417
418            if let Some(value) = content_range_header_value(response.status_code, content_range) {
419                response.headers.push(Header {
420                    name: Header::_CONTENT_RANGE.to_string(),
421                    value,
422                });
423            }
424
425            response.headers.push(Header {
426                name: Header::_CONTENT_LENGTH.to_string(),
427                value: content_range.body.len().to_string()
428            });
429        }
430
431        if response.content_range_list.len() > 1 {
432            let content_range_header_value = [
433                Range::MULTIPART,
434                SYMBOL.slash,
435                Range::BYTERANGES,
436                SYMBOL.semicolon,
437                SYMBOL.whitespace,
438                Range::BOUNDARY,
439                SYMBOL.equals,
440                Range::STRING_SEPARATOR
441            ].join("");
442            response.headers.push(Header {
443                name: Header::_CONTENT_TYPE.to_string(),
444                value: content_range_header_value,
445            });
446        }
447
448        let body = Response::generate_body(response.content_range_list);
449
450        let mut headers_str = SYMBOL.new_line_carriage_return.to_string();
451        for header in response.headers {
452            let mut header_string = SYMBOL.empty_string.to_string();
453            header_string.push_str(&header.name);
454            header_string.push_str(Header::NAME_VALUE_SEPARATOR);
455            header_string.push_str(&header.value);
456            header_string.push_str(SYMBOL.new_line_carriage_return);
457            headers_str.push_str(&header_string);
458        }
459        let status = [response.http_version, response.status_code.to_string(), response.reason_phrase].join(SYMBOL.whitespace);
460        let response_without_body = format!(
461            "{}{}{}",
462            status,
463            headers_str,
464            SYMBOL.new_line_carriage_return,
465        );
466
467        let is_head = request.method == METHOD.head;
468        let is_options = request.method == METHOD.options;
469
470        return if is_head || is_options {
471            response_without_body.into_bytes()
472        } else {
473            [response_without_body.into_bytes(), body].concat()
474        }
475
476    }
477
478    pub fn _parse_response(response_vec_u8: &[u8]) -> Response {
479        let mut cursor = io::Cursor::new(response_vec_u8);
480
481        let mut response = Response {
482            http_version: "".to_string(),
483            status_code: 0,
484            reason_phrase: "".to_string(),
485            headers: vec![],
486            content_range_list: vec![],
487            stream_file: None,
488            stream_pipe: None,
489        };
490
491        let content_length: usize = 0;
492        let iteration_number : usize = 0;
493
494        Response::_parse_raw_response_via_cursor(&mut cursor, iteration_number, &mut response, content_length);
495
496        return response;
497    }
498
499    pub fn _parse_http_version_status_code_reason_phrase_string(http_version_status_code_reason_phrase: &str) -> Result<(String, i16, String), String> {
500        let truncated = StringExt::truncate_new_line_carriage_return(http_version_status_code_reason_phrase);
501
502        let boxed_split = truncated.split_once(SYMBOL.whitespace);
503        if boxed_split.is_none() {
504            return Err(Response::_ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE.to_string())
505        }
506
507        let (http_version, status_code_reason_phrase) = boxed_split.unwrap();
508        let supported_http_versions = HTTP::version_list();
509        if !supported_http_versions.contains(&http_version.to_uppercase().to_string()) {
510            return Err(Response::_ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE.to_string())
511        }
512
513        let boxed_split = status_code_reason_phrase.split_once(SYMBOL.whitespace);
514        if boxed_split.is_none() {
515            return Err(Response::_ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE.to_string())
516        }
517        let (status_code, reason_phrase) = boxed_split.unwrap();
518
519        let boxed_status_code_i16 = status_code.parse::<i16>();
520        if boxed_status_code_i16.is_err() {
521            return Err(Response::_ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE.to_string())
522        }
523
524        let status_code_i16 = boxed_status_code_i16.unwrap();
525
526        let list = Response::status_code_reason_phrase_list();
527        let boxed_search =
528            list
529                .iter()
530                .find(|x| {
531                    return x.status_code == &status_code_i16
532                });
533
534        if boxed_search.is_none() {
535            return Err(Response::_ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE.to_string())
536        }
537
538        let found_status_code_reason_phrase = boxed_search.unwrap();
539        let uppercase_reason_phrase = reason_phrase.to_uppercase();
540        let is_equal =
541            &found_status_code_reason_phrase.reason_phrase
542            .to_uppercase()
543                .eq(uppercase_reason_phrase.as_str());
544
545        if !is_equal {
546            return Err(Response::_ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE.to_string())
547        }
548
549        return Ok((http_version.to_string(), status_code_i16, reason_phrase.to_string()))
550    }
551
552    pub fn _parse_http_response_header_string(header_string: &str) -> Header {
553        let header_parts: Vec<&str> = header_string.split(Header::NAME_VALUE_SEPARATOR).collect();
554        let header_name = header_parts[0].to_string();
555        let raw_header_value = header_parts[1].to_string();
556        let header_value = StringExt::truncate_new_line_carriage_return(&raw_header_value);
557
558
559        Header {
560            name: header_name.to_string(),
561            value: header_value.to_string()
562        }
563    }
564
565    pub fn _parse_raw_response_via_cursor(
566        cursor: &mut Cursor<&[u8]>,
567        mut iteration_number: usize,
568        response: &mut Response,
569        mut content_length: usize) {
570
571        let mut buffer = vec![];
572        let boxed_read = cursor.read_until(b'\n', &mut buffer);
573        if boxed_read.is_err() {
574            eprintln!("unable to parse raw response via cursor {}", boxed_read.err().unwrap());
575            return;
576        }
577        let bytes_offset = boxed_read.unwrap();
578        let mut buffer_as_u8_array: &[u8] = &buffer;
579        let string = String::from_utf8(Vec::from(buffer_as_u8_array)).unwrap();
580
581        let is_first_iteration = iteration_number == 0;
582        let new_line_char_found = bytes_offset != 0;
583        let current_string_is_empty = string.trim().len() == 0;
584
585        if is_first_iteration {
586            let boxed_http_version_status_code_reason_phrase = Response::_parse_http_version_status_code_reason_phrase_string(&string);
587            if boxed_http_version_status_code_reason_phrase.is_err() {
588                let error = boxed_http_version_status_code_reason_phrase.err().unwrap();
589                eprintln!("{}", error);
590                return;
591            }
592
593            let (http_version, status_code, reason_phrase) = boxed_http_version_status_code_reason_phrase.unwrap();
594
595            response.http_version = http_version;
596            response.status_code = status_code;
597            response.reason_phrase = reason_phrase;
598        }
599
600        if current_string_is_empty {
601            let content_type = response._get_header(Header::_CONTENT_TYPE.to_string()).unwrap();
602            let is_multipart = Response::_is_multipart_byteranges_content_type(&content_type);
603
604            if is_multipart {
605                let content_range_list : Vec<ContentRange> = vec![];
606
607                let mut buf = vec![];
608                cursor.read_until(b'\n', &mut buf).unwrap();
609                let boxed_value = Range::_parse_multipart_body(cursor, content_range_list);
610                let mut range_list = vec![];
611                if boxed_value.is_ok() {
612                    range_list = boxed_value.unwrap();
613                }
614                response.content_range_list = range_list;
615            } else {
616                buffer = vec![];
617                let boxed_read = cursor.read_to_end(&mut buffer);
618                if boxed_read.is_ok() {
619                    buffer_as_u8_array = &buffer;
620
621                    let content_range = ContentRange {
622                        unit: Range::BYTES.to_string(),
623                        range: Range {
624                            start: 0,
625                            end: buffer_as_u8_array.len() as u64
626                        },
627                        size: buffer_as_u8_array.len().to_string(),
628                        body: Vec::from(buffer_as_u8_array),
629                        content_type: content_type.value.to_string()
630                    };
631                    response.content_range_list = vec![content_range];
632                } else {
633                    let reason = boxed_read.err().unwrap();
634                    eprintln!("error reading file: {}", reason.to_string())
635                }
636
637            }
638
639            return;
640        }
641
642        if new_line_char_found && !current_string_is_empty {
643            let mut header = Header { name: "".to_string(), value: "".to_string() };
644            if !is_first_iteration {
645                header = Response::_parse_http_response_header_string(&string);
646                if header.name == Header::_CONTENT_LENGTH {
647                    content_length = header.value.parse().unwrap();
648                }
649            }
650
651            response.headers.push(header);
652            iteration_number += 1;
653            Response::_parse_raw_response_via_cursor(cursor, iteration_number, response, content_length);
654        }
655    }
656
657    pub fn _is_multipart_byteranges_content_type(content_type: &Header) -> bool {
658        let multipart_byteranges =
659            [
660                Range::MULTIPART,
661                SYMBOL.slash,
662                Range::BYTERANGES
663            ].join("");
664        let is_multipart_byteranges = content_type.value.starts_with(&multipart_byteranges);
665        is_multipart_byteranges
666    }
667
668
669    pub fn get_response(
670        status_code_reason_phrase: &StatusCodeReasonPhrase,
671        boxed_header_list: Option<Vec<Header>>,
672        boxed_content_range_list: Option<Vec<ContentRange>>) -> Response {
673
674        let mut header_list: Vec<Header> = vec![];
675        if boxed_header_list.is_some() {
676            header_list = boxed_header_list.unwrap();
677        }
678
679        let mut content_range_list: Vec<ContentRange> = vec![];
680        if boxed_content_range_list.is_some() {
681            content_range_list = boxed_content_range_list.unwrap();
682        }
683
684        let response = Response {
685            http_version: VERSION.http_1_1.to_string(),
686            status_code: *status_code_reason_phrase.status_code,
687            reason_phrase: status_code_reason_phrase.reason_phrase.to_string(),
688            headers: header_list,
689            content_range_list,
690            stream_file: None,
691            stream_pipe: None,
692        };
693
694        response
695    }
696
697    /// Build a `Content-Type: application/json` response from already-serialized bytes.
698    ///
699    /// Takes raw bytes rather than a `Serialize` value so it carries no dependency on the
700    /// `serde` feature — pair it with `serde_json::to_vec` (or hand-rolled JSON) to build `body`.
701    /// For a one-line serialize-and-respond helper on a typed value, see [`crate::json::Json`]
702    /// (`serde` feature).
703    ///
704    /// ```rust,no_run
705    /// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
706    ///
707    /// let response = Response::json(STATUS_CODE_REASON_PHRASE.n200_ok, br#"{"ok":true}"#.to_vec());
708    /// ```
709    pub fn json(status_code_reason_phrase: &StatusCodeReasonPhrase, body: Vec<u8>) -> Response {
710        let content_range = Range::get_content_range(body, MimeType::APPLICATION_JSON.to_string());
711        Response::get_response(status_code_reason_phrase, None, Some(vec![content_range]))
712    }
713
714    /// Build a `Content-Type: text/plain` response from a body string.
715    ///
716    /// ```rust,no_run
717    /// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
718    ///
719    /// let response = Response::text(STATUS_CODE_REASON_PHRASE.n400_bad_request, "invalid input");
720    /// ```
721    pub fn text(status_code_reason_phrase: &StatusCodeReasonPhrase, body: &str) -> Response {
722        let content_range = Range::get_content_range(body.as_bytes().to_vec(), MimeType::TEXT_PLAIN.to_string());
723        Response::get_response(status_code_reason_phrase, None, Some(vec![content_range]))
724    }
725
726    pub fn generate(&mut self) -> Vec<u8> {
727        let response = &mut self.clone();
728
729        if response.content_range_list.len() == 1 {
730            let content_range_index = 0;
731            let content_range = response.content_range_list.get(content_range_index).unwrap();
732            response.headers.push(Header {
733                name: Header::_CONTENT_TYPE.to_string(),
734                value: content_range.content_type.to_string()
735            });
736
737            if let Some(value) = content_range_header_value(response.status_code, content_range) {
738                response.headers.push(Header {
739                    name: Header::_CONTENT_RANGE.to_string(),
740                    value,
741                });
742            }
743
744            response.headers.push(Header {
745                name: Header::_CONTENT_LENGTH.to_string(),
746                value: content_range.body.len().to_string()
747            });
748        }
749
750        if response.content_range_list.len() > 1 {
751            let content_range_header_value = [
752                Range::MULTIPART,
753                SYMBOL.slash,
754                Range::BYTERANGES,
755                SYMBOL.semicolon,
756                SYMBOL.whitespace,
757                Range::BOUNDARY,
758                SYMBOL.equals,
759                Range::STRING_SEPARATOR
760            ].join("");
761            response.headers.push(Header {
762                name: Header::_CONTENT_TYPE.to_string(),
763                value: content_range_header_value,
764            });
765        }
766
767        let response_clone = response.clone();
768        let body = Response::generate_body(response_clone.content_range_list);
769
770        let mut headers_str = SYMBOL.new_line_carriage_return.to_string();
771
772        let header_list = response.headers.clone();
773        for header in header_list {
774            let mut header_string = SYMBOL.empty_string.to_string();
775            header_string.push_str(&header.name);
776            header_string.push_str(Header::NAME_VALUE_SEPARATOR);
777            header_string.push_str(&header.value);
778            header_string.push_str(SYMBOL.new_line_carriage_return);
779            headers_str.push_str(&header_string);
780        }
781
782        let response_clone = response.clone();
783        let status = [response_clone.http_version, response.status_code.to_string(), response_clone.reason_phrase].join(SYMBOL.whitespace);
784        let response_without_body = format!(
785            "{}{}{}",
786            status,
787            headers_str,
788            SYMBOL.new_line_carriage_return,
789        );
790
791
792        [response_without_body.into_bytes(), body].concat()
793    }
794
795    pub fn get_header(&self, name: String) -> Option<&Header> {
796        self._get_header(name)
797    }
798
799    pub fn parse(response_vec_u8: &[u8]) -> Result<Response, String> {
800        let total_bytes : i32 = response_vec_u8.len() as i32;
801        let bytes_read = 0;
802        let mut cursor = io::Cursor::new(response_vec_u8);
803
804        let mut response = Response {
805            http_version: "".to_string(),
806            status_code: 0,
807            reason_phrase: "".to_string(),
808            headers: vec![],
809            content_range_list: vec![],
810            stream_file: None,
811            stream_pipe: None,
812        };
813
814        let content_length: usize = 0;
815        let iteration_number : usize = 0;
816
817        let boxed_parse = Response::parse_raw_response_via_cursor(
818            &mut cursor, iteration_number,
819            &mut response,
820            content_length,
821            total_bytes,
822            bytes_read
823        );
824        if boxed_parse.is_err() {
825            let message = boxed_parse.err().unwrap();
826            return Err(message);
827        }
828
829        return Ok(response);
830    }
831
832    pub fn parse_raw_response_via_cursor(
833        cursor: &mut Cursor<&[u8]>,
834        mut iteration_number: usize,
835        response: &mut Response,
836        mut content_length: usize,
837        total_bytes: i32,
838        mut bytes_read: i32) -> Result<(), String> {
839
840        let mut buffer = vec![];
841        let boxed_read = cursor.read_until(b'\n', &mut buffer);
842        if boxed_read.is_err() {
843            let message = format!("unable to parse raw response via cursor {}", boxed_read.err().unwrap());
844            return Err(message);
845        }
846        let bytes_offset = boxed_read.unwrap();
847        bytes_read = bytes_read + bytes_offset as i32;
848        if bytes_read == total_bytes {
849            // end of stream
850        }
851        let mut buffer_as_u8_array: &[u8] = &buffer;
852        let boxed_string = String::from_utf8(Vec::from(buffer_as_u8_array));
853        if boxed_string.is_err() {
854            let message = boxed_string.err().unwrap().to_string();
855            return Err(message);
856        }
857        let string = boxed_string.unwrap();
858
859        let is_first_iteration = iteration_number == 0;
860        let new_line_char_found = bytes_offset != 0;
861        let current_string_is_empty = string.trim().len() == 0;
862
863        if is_first_iteration {
864            let boxed_http_version_status_code_reason_phrase = Response::_parse_http_version_status_code_reason_phrase_string(&string);
865            if boxed_http_version_status_code_reason_phrase.is_err() {
866                let message = boxed_http_version_status_code_reason_phrase.err().unwrap();
867                return Err(message);
868            }
869
870            let (http_version, status_code, reason_phrase) = boxed_http_version_status_code_reason_phrase.unwrap();
871
872            response.http_version = http_version;
873            response.status_code = status_code;
874            response.reason_phrase = reason_phrase;
875        }
876
877        if current_string_is_empty {
878            let mut is_multipart = false;
879            // if response does not contain Content-Type, it will be defaulted to APPLICATION_OCTET_STREAM
880            let mut content_type = MimeType::APPLICATION_OCTET_STREAM;
881
882            let boxed_content_type = response.get_header(Header::_CONTENT_TYPE.to_string());
883            if boxed_content_type.is_some() {
884                let content_type_header = response.get_header(Header::_CONTENT_TYPE.to_string()).unwrap();
885                content_type = content_type_header.value.as_str();
886                is_multipart = Response::_is_multipart_byteranges_content_type(&content_type_header);
887            }
888
889
890            if is_multipart {
891                let content_range_list : Vec<ContentRange> = vec![];
892                let boxed_content_type = response.get_header(Header::_CONTENT_TYPE.to_string());
893                if boxed_content_type.is_none() {
894                    return Err("Content-Type is missing".to_string());
895                }
896                let content_type = boxed_content_type.unwrap();
897                let boxed_boundary = FormMultipartData::extract_boundary(content_type.value.as_str());
898                if boxed_boundary.is_err() {
899                    return Err("unable to extract boundary from Content-Type".to_string());
900                }
901                let boundary = boxed_boundary.unwrap();
902
903                let is_opening_boundary_read = false;
904                let boxed_content_range_list =
905                    Range::parse_multipart_body_with_boundary(
906                        cursor,
907                        content_range_list,
908                        boundary,
909                        total_bytes,
910                        bytes_read,
911                        is_opening_boundary_read);
912                if boxed_content_range_list.is_err() {
913                    let message = boxed_content_range_list.err().unwrap();
914                    return Err(message);
915                }
916
917                response.content_range_list = boxed_content_range_list.unwrap();
918            } else {
919                buffer = vec![];
920                let boxed_read = cursor.read_to_end(&mut buffer);
921                if boxed_read.is_err() {
922                    let message = boxed_read.err().unwrap().to_string();
923                    return Err(message);
924                }
925                let bytes_offset = boxed_read.unwrap();
926                bytes_read = bytes_read + bytes_offset as i32;
927                if bytes_read == total_bytes {
928                    // end of stream
929                }
930
931                buffer_as_u8_array = &buffer;
932
933                let content_range = ContentRange {
934                    unit: Range::BYTES.to_string(),
935                    range: Range {
936                        start: 0,
937                        end: buffer_as_u8_array.len() as u64
938                    },
939                    size: buffer_as_u8_array.len().to_string(),
940                    body: Vec::from(buffer_as_u8_array),
941                    content_type: content_type.to_string()
942                };
943                response.content_range_list = vec![content_range];
944
945
946            }
947
948            return Ok(());
949        }
950
951        if new_line_char_found && !current_string_is_empty {
952            if !is_first_iteration {
953                let boxed_header = Response::parse_http_response_header_string(&string);
954                if boxed_header.is_err() {
955                    let message = boxed_header.err().unwrap();
956                    return Err(message);
957                }
958                let header = boxed_header.unwrap();
959                if header.name == Header::_CONTENT_LENGTH {
960                    content_length = header.value.parse().unwrap();
961                }
962                response.headers.push(header);
963            }
964
965            iteration_number += 1;
966            return Response::parse_raw_response_via_cursor(cursor, iteration_number, response, content_length, total_bytes, bytes_read );
967        } else {
968            return Err("unable to parse".to_string());
969        }
970    }
971
972    pub fn parse_http_response_header_string(header_string: &str) -> Result<Header, String> {
973        let header_parts: Option<(&str, &str)> = header_string.split_once(Header::NAME_VALUE_SEPARATOR);
974        if header_parts.is_none() {
975            let message = format!("unable to parse header: {}", header_string);
976            return Err(message);
977        }
978        let (header_name, raw_header_value) = header_parts.unwrap();
979        let header_value = StringExt::truncate_new_line_carriage_return(&raw_header_value);
980
981        Ok(Header {
982            name: header_name.to_string(),
983            value: header_value.to_string()
984        })
985    }
986}
987
988impl New for Response {
989    fn new() -> Self {
990        Response {
991            http_version: VERSION.http_1_1.to_string(),
992            status_code: *STATUS_CODE_REASON_PHRASE.n501_not_implemented.status_code,
993            reason_phrase: STATUS_CODE_REASON_PHRASE.n501_not_implemented.reason_phrase.to_string(),
994            headers: vec![],
995            content_range_list: vec![],
996            stream_file: None,
997            stream_pipe: None,
998        }
999    }
1000}