Skip to content

Instantly share code, notes, and snippets.

@compscitwilight
Last active April 13, 2024 05:40
Show Gist options
  • Save compscitwilight/da41bcd9d68e11830bbfdcc316688670 to your computer and use it in GitHub Desktop.
Save compscitwilight/da41bcd9d68e11830bbfdcc316688670 to your computer and use it in GitHub Desktop.
// my very first Rust program
// an HTTP server which nobody should *ever* use
use std::io::*;
use std::path::Path;
use std::thread;
use std::fs;
use std::env;
use std::str;
use std::net::{TcpListener, TcpStream};
fn respond(file: &str, stream: &mut TcpStream) {
let mut response = String::new();
let wd = env::current_dir().unwrap().into_os_string().into_string().unwrap();
let path = Path::new(&wd).join("src").join(&file[1..]);
let bytes = fs::read(path);
match bytes {
Ok(bytes) => {
let byte_arr = &*bytes;
response.push_str("HTTP/1.1 200 OK\r\n");
response.push_str("Content-Type: text/html;\r\n\n");
response.push_str(&String::from_utf8_lossy(byte_arr));
}
Err(_) => {
response.push_str("HTTP/1.1 404 Not Found\r\n");
}
}
stream.write(response.as_bytes()).expect("Failure to send response to client.");
}
fn handle_request(stream: &mut TcpStream) {
let mut buf: [u8; 256] = [0; 256];
stream.read(&mut buf).expect("Failed to read stream from HTTP client.");
let buf_str = str::from_utf8(&buf).unwrap().to_string();
let mut path: &str = "";
for (index, chr) in buf_str.chars().enumerate() {
if chr == 'H' {
path = &buf_str[4..index - 1];
break;
}
}
respond(path, stream);
}
fn main() {
let server = TcpListener::bind("127.0.0.1:8080")
.expect("Failed to start HTTP socket server.");
println!("Server bound to port 8080.");
for stream in server.incoming() {
match stream {
Ok(mut s) => {
thread::Builder::new().name("connection".to_string()).spawn(move || {
handle_request(&mut s);
});
},
Err(_) => println!("Connection failed for a client.")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment