I’m stuck on Stage #QV8
I’ve tried a lot of things, all the parsing is working perfectly, however my body parsing is still not working, somehow it’s always an empty string. I am trying to create a struct HTTPRequest with the input of the bufReader. (Please be advised I am a beginner in Rust so maybe you see some crazy thing here)
And here’s a snippet of my code:
struct HTTPRequest<'a> {
method: &'a str,
version: &'a str,
route: &'a str,
headers: Vec<(&'a str, String)>,
content_length: u64,
body: String,
}
impl<'a> HTTPRequest<'a> {
fn from_lines(lines: impl Iterator<Item=&'a str>) -> HTTPRequest<'a> {
let mut lines = lines.peekable();
// Parse the request line
let request_line = lines.next().unwrap_or("");
let mut request_parts = request_line.split_whitespace();
let method = request_parts.next().unwrap_or("");
let route = request_parts.next().unwrap_or("");
let version = request_parts.next().unwrap_or("");
// Collect the body
let mut body = String::new();
// Parse headers
let mut headers = Vec::new();
let mut content_length = 0;
while let Some(line) = lines.next() {
if line.is_empty() {
break; // Stop processing headers on encountering a blank line
}
if let Some((name, value)) = line.split_once(": ") {
headers.push((name, value.to_string()));
if name.to_lowercase() == "content-length" {
content_length = value.trim().parse().unwrap_or(0); // Parse Content-Length header
}
} else {
body.push_str(line);
}
}
HTTPRequest {
method,
version,
route,
headers,
content_length,
body,
}
}
fn get_header_value(&self, key: &str) -> Option<&str> {
for (name, value) in &self.headers {
if *name == key {
return Some(value);
}
}
None
}
}
And I call it here:
let mut buf_reader = BufReader::new(&mut stream);
let mut request_lines = Vec::new();
for line in buf_reader.by_ref().lines() {
let line = line.unwrap();
if line.is_empty() {
break;
}
request_lines.push(line);
}
let request = HTTPRequest::from_lines(request_lines.iter().map(|s| s.as_str()));
Just in case someone wants to run it you have the full code here: