تمرين إعادة البناء
HTTP Request Parser
أعد كتابة محلل طلب HTTP صغير يقرأ السطر الأول والرؤوس.
rust
~22 دقيقة
متوسط
أعد بناء الكود
Rebuild
هذا هو الكود. اكتبه بنفسك.
الكود المرجعي
use std::collections::BTreeMap;
use std::io::{self, Read};
#[derive(Debug)]
struct Request {
method: String,
path: String,
version: String,
headers: BTreeMap<String, String>,
}
fn main() -> io::Result<()> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
if input.trim().is_empty() {
input = "GET /products?city=riyadh HTTP/1.1\r\nHost: example.test\r\nAccept: text/html\r\n\r\n".to_string();
}
match parse_request(&input) {
Some(request) => {
println!("Method: {}", request.method);
println!("Path: {}", request.path);
println!("Version: {}", request.version);
for (name, value) in request.headers {
println!("{name}: {value}");
}
}
None => println!("Invalid request"),
}
Ok(())
}
fn parse_request(input: &str) -> Option<Request> {
let mut lines = input.lines();
let first = lines.next()?;
let mut parts = first.split_whitespace();
let method = parts.next()?.to_string();
let path = parts.next()?.to_string();
let version = parts.next()?.to_string();
let mut headers = BTreeMap::new();
for line in lines {
if line.trim().is_empty() {
break;
}
let (name, value) = line.split_once(':')?;
headers.insert(name.trim().to_string(), value.trim().to_string());
}
Some(Request {
method,
path,
version,
headers,
})
}اكتب هنا