http-server-cc/src/main.rs

117 lines
3.1 KiB
Rust
Raw Normal View History

2024-05-10 18:37:00 +00:00
// #![feature(if_let_guard)]
2024-05-10 18:33:15 +00:00
2024-05-10 20:27:11 +00:00
use std::collections::HashMap;
2024-05-10 17:50:36 +00:00
use anyhow::Result;
2024-05-10 17:06:42 +00:00
2024-05-10 20:27:11 +00:00
use tokio::{
io::{ AsyncBufReadExt, AsyncWriteExt, BufReader, Lines },
net::{ TcpListener, TcpStream }
};
2024-05-10 19:29:51 +00:00
mod utils;
use utils::*;
2024-05-10 17:50:36 +00:00
2024-05-10 20:27:11 +00:00
#[tokio::main]
async fn main() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:4221").await.unwrap();
2024-05-10 17:23:14 +00:00
2024-05-10 20:27:11 +00:00
loop {
let Ok((socket, info)) = listener.accept().await else { continue; } ;
println!("Connection from {:?} accepted, processing…", info);
let _ = process(socket).await;
}
2024-05-10 17:50:36 +00:00
2024-05-10 20:27:11 +00:00
}
2024-05-10 17:50:36 +00:00
2024-05-10 20:27:11 +00:00
async fn process (mut stream: TcpStream) -> Result<()> {
let buf_reader = BufReader::new(&mut stream);
2024-05-10 17:50:36 +00:00
2024-05-10 20:27:11 +00:00
let mut data = buf_reader
.lines();
2024-05-10 19:29:51 +00:00
2024-05-10 20:27:11 +00:00
let (_method, path, _ver) = {
let start_line = data.next_line().await?.ok_or(E::InvalidRequest)?; // should be 500;
let mut parts = start_line.split_whitespace().map(ToOwned::to_owned);
let method = parts.next().ok_or(E::InvalidRequest)?;
let path = parts.next().ok_or(E::InvalidRequest)?;
let ver = parts.next().ok_or(E::InvalidRequest)?;
2024-05-10 19:29:51 +00:00
2024-05-10 20:27:11 +00:00
(method, path, ver)
};
2024-05-10 17:50:36 +00:00
2024-05-10 20:27:11 +00:00
let headers = Headers::parse(data.into_inner()).await;
2024-05-10 17:50:36 +00:00
2024-05-10 20:27:11 +00:00
let response = match path.as_str() {
"/" => Response::Empty,
"/user-agent" => Response::TextPlain(headers.get("User-Agent")),
// p if let Some(echo) = p.strip_prefix("/echo/") => Response::TextPlain(echo), // a nicer way to do that, not available in stable yet
p if p.starts_with("/echo/") => Response::TextPlain(p.trim_start_matches("/echo/")),
_ => Response::_404,
};
println!("{:?}", response);
let _ = stream.write_all(response.build().as_bytes()).await;
let _ = stream.flush().await;
2024-05-10 17:50:36 +00:00
Ok(())
}
2024-05-10 20:27:11 +00:00
#[derive(Debug, Clone)]
2024-05-10 19:29:51 +00:00
pub struct Headers (HashMap<String, String>);
impl Headers {
2024-05-10 20:27:11 +00:00
pub async fn parse (mut reader: BufReader<&'_ mut TcpStream>) -> Self {
let mut map = HashMap::new();
let mut buf = String::new();
while let Ok(_) = reader.read_line(&mut buf).await {
if let Some((k, v)) = buf.split_once(":") {
println!("{:?}", (k, v));
map.insert(k.trim().to_lowercase(), v.trim().to_owned());
} else {
break;
}
buf.clear();
}
Self(map)
2024-05-10 19:29:51 +00:00
}
pub fn get <'a> (&'a self, key: &str) -> &'a str {
self.0.get(&key.to_lowercase()).map(|e| e.as_str()).unwrap_or_default()
}
}
2024-05-10 18:33:15 +00:00
#[derive(Debug, Clone)]
enum Response <'a> {
_404,
Empty,
TextPlain (&'a str),
}
#[allow(non_upper_case_globals)]
impl Response <'_> {
fn build (self) -> String {
let (code, body) = match self {
Self::_404 => ("404 Not Found", d!()),
Self::Empty => ("200 OK", d!()),
Self::TextPlain(text) => ("200 OK", text)
};
2024-05-10 17:50:36 +00:00
2024-05-10 18:33:15 +00:00
let headers = self.headers().join("\r\n");
f!("HTTP/1.1 {code}\r\n{headers}\r\n\r\n{body}").into()
}
fn headers (&self) -> Vec<String> {
match self {
Self::TextPlain(text) => vec![f!("Content-Type: text/plain"), format!("Content-Length: {}", text.len())],
_ => d!()
}
}
2024-05-10 17:06:42 +00:00
}