RustBrock/hello/src/main.rs
darkicewolf50 732235ab69
All checks were successful
Test Gitea Actions / first (push) Successful in 21s
Test Gitea Actions / check-code (push) Successful in 17s
Test Gitea Actions / test (push) Successful in 17s
Test Gitea Actions / documentation-check (push) Successful in 16s
finsihed The Rust Programming Language Bookgit add -Agit add -A
2025-04-18 16:14:55 -06:00

75 lines
2.2 KiB
Rust

use std::{
fs,
io::{ prelude::*, BufReader },
net::{ TcpListener, TcpStream },
thread,
time::Duration,
};
use hello::ThreadPool;
fn main() {
// this is not related I was just curious
// let test = fs::read_to_string("test.yaml").unwrap();
// println!("{}", test);
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().take(2) {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
println!("Shutting down.");
}
fn handle_connection(mut stream: TcpStream) {
let buf_reader = BufReader::new(&stream);
// let http_request: Vec<_> = buf_reader
// .lines()
// .map(|result| result.unwrap())
// .take_while(|line| !line.is_empty())
// .collect();
let request_line = buf_reader.lines().next().unwrap().unwrap();
// no longer needed, here for debug and being useful
// println!("Request: {:#?}", http_request);
// if request_line == "GET / HTTP/1.1" {
// let status_line = "HTTP/1.1 200 OK";
// let contents = fs::read_to_string("./hello.html").unwrap();
// let length = contents.len();
// let res = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
// stream.write_all(res.as_bytes()).unwrap();
// } else {
// let status_line = "HTTP/1.1 404 NOT FOUND";
// let contents = fs::read_to_string("404.html").unwrap();
// let length = contents.len();
// let res = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
// stream.write_all(res.as_bytes()).unwrap();
// }
let (status_line, filename) = match &request_line[..] {
"GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
"GET /sleep HTTP/1.1" => {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
}
_ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
};
let contents = fs::read_to_string(filename).unwrap();
let length = contents.len();
let res = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
stream.write_all(res.as_bytes()).unwrap();
}