Implement per-stream threading

This commit is contained in:
abbie 2021-12-24 21:30:39 +00:00
parent 7ad6eb64b3
commit 8088fcdde6
No known key found for this signature in database
GPG key ID: 04DDE463F9200F87
3 changed files with 31 additions and 28 deletions

2
Cargo.lock generated
View file

@ -2,4 +2,4 @@
# It is not intended for manual editing.
[[package]]
name = "herb"
version = "0.1.2"
version = "0.1.4"

View file

@ -1,6 +1,6 @@
[package]
name = "herb"
version = "0.1.3"
version = "0.2.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View file

@ -1,4 +1,5 @@
use std::io::{Write, BufReader, BufRead};
use std::thread;
use std::net::{TcpListener, TcpStream};
use std::fs;
use std::string::{String};
@ -183,40 +184,42 @@ fn process_request(request: Vec<u8>) -> String {
}
fn serve(mut stream: TcpStream) {
let mut request = Vec::new();
let mut reader = BufReader::new(&mut stream);
reader
.read_until(b'\n', &mut request)
.expect("Failed to read from stream!");
thread::spawn(move || {
println!("Stream thread created.");
let mut request = Vec::new();
let mut reader = BufReader::new(&mut stream);
reader
.read_until(b'\n', &mut request)
.expect("Failed to read from stream!");
let resource = process_request(request);
let resource = process_request(request);
// Haha, bodged my way around Rust's ownership paradigm!
let mime = detect_media_type(resource.to_string());
// Haha, bodged my way around Rust's ownership paradigm!
let mime = detect_media_type(resource.to_string());
let contents = get_page(resource);
let header = "HTTP/1.1 200 OK\r\n";
let content_type = format!("Content-Type: {}\r\n", mime);
let server = "Server: Herb/0.1.4\r\n";
let extra_fields;
let contents = get_page(resource);
let header = "HTTP/1.1 200 OK\r\n";
let content_type = format!("Content-Type: {}\r\n", mime);
let server = "Server: Herb/0.2.0\r\n";
let extra_fields;
if cfg!(unix) {
let mut time = format!("Date: {}\r\n", grab_time());
time = time.replace("'","");
extra_fields = format!("{}{}\r\n", server, time);
} else {
// I don't have a Windows or macOS box to test anything on
// which means others are gonna have to deal with it :/
if cfg!(unix) {
let mut time = format!("Date: {}\r\n", grab_time());
time = time.replace("'","");
extra_fields = format!("{}{}\r\n", server, time);
} else {
// I don't have a Windows or macOS box to test anything on
// which means others are gonna have to deal with it :/
extra_fields = format!("{}\r\n", server);
}
extra_fields = format!("{}\r\n", server);
}
let response = format!("{}{}{}{}", header, content_type, extra_fields, contents);
let response = format!("{}{}{}{}", header, content_type, extra_fields, contents);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
});
}