Created
July 22, 2023 16:02
-
-
Save foriequal0/b97dbb5e9c9172c8888de83452c8a19f to your computer and use it in GitHub Desktop.
blocking, synchronous, single thread, non-buffered http server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fs::File; | |
use std::io::{Read, Write}; | |
use std::net::{TcpListener, TcpStream}; | |
use rand::Rng; | |
use stream_httparse::streaming_parser::ReqParser; | |
fn main() -> std::io::Result<()>{ | |
let listener = TcpListener::bind("127.0.0.1:8080")?; | |
for stream in listener.incoming() { | |
let _ = handle_client(stream?); | |
} | |
Ok(()) | |
} | |
fn handle_client(mut stream: TcpStream) -> std::io::Result<()> { | |
drain_http(&mut stream)?; | |
let r = rand::thread_rng().gen_range(0..1000); | |
let mut file = File::open(format!("data/{r}"))?; | |
write!(&mut stream, "HTTP/1.1 200 OK\r\n")?; | |
write!(&mut stream, "Content-Length: 1024\r\n")?; | |
write!(&mut stream, "\r\n")?; | |
std::io::copy(&mut file, &mut stream)?; | |
Ok(()) | |
} | |
fn drain_http(stream: &mut dyn Read) -> std::io::Result<()> { | |
let mut buf = [0u8; 128]; | |
let mut parse = ReqParser::new_capacity(128); | |
loop { | |
let len = stream.read(&mut buf)?; | |
if len == 0 { | |
break; | |
} | |
if let (true,_) = parse.block_parse(&buf[..len]) { | |
break; | |
} | |
} | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment