aboutsummaryrefslogtreecommitdiff
path: root/src/response.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/response.rs')
-rw-r--r--src/response.rs53
1 files changed, 53 insertions, 0 deletions
diff --git a/src/response.rs b/src/response.rs
index 4219afd..c3540d2 100644
--- a/src/response.rs
+++ b/src/response.rs
@@ -38,3 +38,56 @@ impl Into<String> for Response {
format!("{status_line}\r\n{headers}\r\n{body}")
}
}
+
+impl Into<Response> for &str {
+ fn into(self) -> Response {
+ let mut lines = self.lines();
+
+ // Parse the status line
+ let status_line = lines.next().unwrap_or_default();
+ let mut status_line_parts = status_line.split_whitespace();
+
+ let version = status_line_parts.next().unwrap_or_default().to_string();
+ let status_code = status_line_parts.next().unwrap_or_default();
+
+ let status = match status_code {
+ "200" => StatusCode::Ok,
+ "404" => StatusCode::NotFound,
+ _ => StatusCode::Ok,
+ };
+
+ // Parse headers
+ let mut headers_map = HashMap::new();
+ while let Some(line) = lines.next() {
+ if line.is_empty() {
+ break;
+ }
+ let mut parts = line.splitn(2, ':');
+ let key = parts.next().unwrap_or_default().trim();
+ let value = parts.next().unwrap_or_default().trim();
+ headers_map.insert(key.to_string(), value.to_string());
+ }
+ let headers = if headers_map.is_empty() {
+ None
+ } else {
+ Some(Headers(headers_map))
+ };
+
+ // Parse body
+ let body: Option<String> = {
+ let remaining_lines: Vec<&str> = lines.collect();
+ if remaining_lines.is_empty() {
+ None
+ } else {
+ Some(remaining_lines.join("\n"))
+ }
+ };
+
+ Response {
+ version,
+ status,
+ headers,
+ body,
+ }
+ }
+}