http-server-cc/src/main.rs

57 lines
1.6 KiB
Rust
Raw Normal View History

2024-05-10 17:50:36 +00:00
use std::{ fmt::Display, io::{Read, Write}, net::TcpListener };
use anyhow::Result;
use thiserror::Error;
2024-05-10 17:06:42 +00:00
2024-05-10 17:50:36 +00:00
#[derive(Clone, Debug, Error)]
enum E {
#[error("Invalid request data found during parsing")]
InvalidRequest,
}
fn main() -> Result<()> {
2024-05-10 17:23:14 +00:00
let listener = TcpListener::bind("127.0.0.1:4221").unwrap();
for stream in listener.incoming() {
match stream {
2024-05-10 17:26:28 +00:00
Ok(mut stream) => {
2024-05-10 17:50:36 +00:00
let mut buf = String::new();
let _read = stream.read_to_string(&mut buf);
let mut data = buf.split("\r\n");
let _start @ (_method, path, _ver) = {
let start_line = data.next().ok_or(E::InvalidRequest)?; // should be 500;
let mut parts = start_line.split_whitespace();
let method = parts.next().ok_or(E::InvalidRequest)?;
let path = parts.next().ok_or(E::InvalidRequest)?;
let ver = parts.next().ok_or(E::InvalidRequest)?;
(method, path, ver)
};
let code = match path {
"/" => "200 OK",
_ => "404 Not Found",
};
2024-05-10 17:23:14 +00:00
println!("accepted new connection");
2024-05-10 17:50:36 +00:00
let resp = create_response_simple(code);
let _ = stream.write(&resp);
let _ = stream.flush();
2024-05-10 17:23:14 +00:00
}
Err(e) => {
println!("error: {}", e);
}
}
}
2024-05-10 17:50:36 +00:00
Ok(())
}
fn create_response_simple <T> (code: T) -> Vec<u8> where T: Display {
format!("HTTP/1.1 {code}\r\n\r\n").into()
2024-05-10 17:06:42 +00:00
}