http_request/response/
impl.rs1use super::*;
2
3impl Default for HttpResponse {
5 fn default() -> Self {
10 Self {
11 version: HttpVersion::default(),
12 status_code: HttpStatus::Unknown.code(),
13 reason_phrase: HttpStatus::Unknown.to_string(),
14 headers: new_response_headers(),
15 body: ResponseBody::new(),
16 }
17 }
18}
19
20impl HttpResponse {
22 pub fn from_bytes(response: &[u8]) -> Self {
29 let split_lines: Vec<&[u8]> = split_multi_byte(response, HTTP_BR_BYTES);
30 let mut lines: IntoIter<&[u8]> = split_lines.into_iter();
31 let status_line: &[u8] = lines.next().unwrap_or(&[]);
32 let status_parts: Vec<&[u8]> = split_whitespace(status_line);
33 let version: HttpVersion = status_parts
34 .first()
35 .and_then(|part: &&[u8]| from_utf8(part).ok())
36 .and_then(|version_str: &str| version_str.parse::<HttpVersion>().ok())
37 .unwrap_or_default();
38 let status_code: ResponseStatusCode = status_parts
39 .get(1)
40 .and_then(|part: &&[u8]| from_utf8(part).ok())
41 .and_then(|code_str: &str| code_str.parse().ok())
42 .unwrap_or(HttpStatus::Unknown.code());
43 let reason_phrase: String = status_parts.get(2..).map_or_else(
44 || HttpStatus::Unknown.to_string(),
45 |parts: &[&[u8]]| {
46 if parts.is_empty() {
47 HttpStatus::Unknown.to_string()
48 } else if parts.len() == 1 {
49 String::from_utf8_lossy(parts[0]).into_owned()
50 } else {
51 let total_len: usize =
52 parts.iter().map(|p: &&[u8]| p.len()).sum::<usize>() + parts.len() - 1;
53 let mut result: String = String::with_capacity(total_len);
54 for (i, part) in parts.iter().enumerate() {
55 if i > 0 {
56 result.push(' ');
57 }
58 result.push_str(&String::from_utf8_lossy(part));
59 }
60 result
61 }
62 },
63 );
64 let mut headers: HttpResponseHeaders = new_response_headers();
65 for line in lines.by_ref() {
66 if line.is_empty() {
67 break;
68 }
69 let mut colon_pos: Option<usize> = None;
70 for (i, &byte) in line.iter().enumerate() {
71 if byte == COLON_U8 {
72 colon_pos = Some(i);
73 break;
74 }
75 }
76 if let Some(pos) = colon_pos
77 && pos > 0
78 && pos + 1 < line.len()
79 {
80 let key_bytes: &[u8] = &line[..pos];
81 let value_start: usize = if line.get(pos + 1) == Some(&SPACE_U8) {
82 pos + 2
83 } else {
84 pos + 1
85 };
86 let value_bytes: &[u8] = &line[value_start..];
87 if let (Ok(key_str), Ok(value_str)) = (from_utf8(key_bytes), from_utf8(value_bytes))
88 {
89 headers.insert(
90 key_str.trim().to_ascii_lowercase(),
91 value_str.trim().to_owned(),
92 );
93 }
94 }
95 }
96 let body: ResponseBody = match lines.len() {
97 0 => ResponseBody::new(),
98 1 => {
99 let line: &[u8] = lines.next().unwrap_or(&[]);
100 line.to_vec()
101 }
102 _ => {
103 let lines_slice: &[&[u8]] = lines.as_slice();
104 let total_size: usize = lines_slice
105 .iter()
106 .map(|line: &&[u8]| line.len())
107 .sum::<usize>()
108 + lines_slice.len().saturating_sub(1) * BR_BYTES.len();
109 let mut body: ResponseBody = ResponseBody::with_capacity(total_size);
110 let mut first: bool = true;
111 for line in lines {
112 if !first {
113 body.extend_from_slice(BR_BYTES);
114 }
115 body.extend_from_slice(line);
116 first = false;
117 }
118 body
119 }
120 };
121 HttpResponse {
122 version,
123 status_code,
124 reason_phrase,
125 headers,
126 body,
127 }
128 }
129
130 pub fn is_success(&self) -> bool {
136 (200..300).contains(&self.get_status_code())
137 }
138
139 pub fn is_redirect(&self) -> bool {
145 (300..400).contains(&self.get_status_code())
146 }
147
148 pub fn is_client_error(&self) -> bool {
154 (400..500).contains(&self.get_status_code())
155 }
156
157 pub fn is_server_error(&self) -> bool {
163 (500..600).contains(&self.get_status_code())
164 }
165
166 pub fn get_header<K>(&self, key: K) -> Option<&str>
176 where
177 K: AsRef<str>,
178 {
179 let raw: &str = key.as_ref();
180 let bytes: &[u8] = raw.as_bytes();
181 if !bytes.iter().any(|b: &u8| b.is_ascii_uppercase()) {
182 return self.get_headers().get(raw).map(String::as_str);
183 }
184 if bytes.len() <= RESPONSE_HEADER_STACK_LIMIT {
185 let mut stack_buf: [u8; RESPONSE_HEADER_STACK_LIMIT] = [0; RESPONSE_HEADER_STACK_LIMIT];
186 for (idx, &byte) in bytes.iter().enumerate() {
187 stack_buf[idx] = byte.to_ascii_lowercase();
188 }
189 if let Ok(lower) = from_utf8(&stack_buf[..bytes.len()]) {
190 return self.get_headers().get(lower).map(String::as_str);
191 }
192 }
193 let normalized: String = raw.to_ascii_lowercase();
194 self.get_headers().get(&normalized).map(String::as_str)
195 }
196
197 pub fn text(&self) -> String {
203 String::from_utf8_lossy(self.get_body()).into_owned()
204 }
205
206 pub fn bytes(&self) -> &[u8] {
212 self.get_body()
213 }
214
215 pub fn json<T>(&self) -> Result<T, serde_json::Error>
221 where
222 T: DeserializeOwned,
223 {
224 from_slice(self.get_body())
225 }
226
227 pub fn try_get_cookies(&self) -> Option<Cookies> {
233 let header: &str = self.get_header(SET_COOKIE)?;
234 let parsed: CookieBuilder = CookieBuilder::parse(header);
235 let mut cookies: Cookies = hash_map_xx_hash3_64();
236 if !parsed.get_name().is_empty() {
237 cookies.insert(parsed.get_name().clone(), parsed.get_value().clone());
238 }
239 Some(cookies)
240 }
241
242 pub fn decode(&self, buffer_size: usize) -> HttpResponse {
255 let decoded: ResponseBody = Compress::from(self.get_headers())
256 .decode(self.get_body(), buffer_size)
257 .into_owned();
258 HttpResponse {
259 version: self.get_version().clone(),
260 status_code: self.get_status_code(),
261 reason_phrase: self.get_reason_phrase().clone(),
262 headers: self.get_headers().clone(),
263 body: decoded,
264 }
265 }
266}