Skip to content

Instantly share code, notes, and snippets.

@codesections
Last active March 20, 2022 04:35
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codesections/71893961840f5bd080225eafe063afd8 to your computer and use it in GitHub Desktop.
Save codesections/71893961840f5bd080225eafe063afd8 to your computer and use it in GitHub Desktop.
Naive static file server in rust
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
mod app;
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
}
}
fn handle_connection(mut stream: TcpStream) {
let request = used::req(&stream);
let response = used::serve_static(&request[..], "./public");
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
pub mod used {
use std::fs;
use std::io::prelude::*;
use std::net::TcpStream;
struct HttpHeader {
ok: String,
not_found: String,
}
pub fn serve_static(req: &str, dir: &str) -> String {
let res = HttpHeader {
ok: String::from("HTTP/1.1 200 OK\r\n\r\n"),
not_found: String::from("HTTP/1.1 404 Not Found\r\n\r\n"),
};
let paths = vec![
(format!("{}{}{}", dir, req, "/index.html"), &res.ok),
(format!("{}{}", dir, req), &res.ok),
(format!("./public/404.html"), &res.not_found),
];
let mut contents = String::from("<h1>404 File Not Found.</h1>");
let mut header = &res.not_found;
for path in paths {
let file_contents = fs::read_to_string(path.0);
if let Ok(file) = file_contents {
contents = file;
header = path.1;
break;
};
}
format!("{}{}", header, contents)
}
pub fn req(mut stream: &TcpStream) -> String {
let mut buffer: [u8; 512] = [0; 512];
stream.read(&mut buffer).unwrap();
let mut request = String::from("error");
for i in 0..500 {
if String::from_utf8_lossy(&buffer[i..i + 5]) == " HTTP" {
request = String::from_utf8_lossy(&buffer[4..i]).to_string();
break;
}
}
request
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment