Skip to content
Snippets Groups Projects
Commit 9b9f4971 authored by codecraft's avatar codecraft :crocodile:
Browse files

Add MIME support for the handler

update routeing module
parent d319f18d
No related branches found
No related tags found
No related merge requests found
...@@ -86,6 +86,7 @@ name = "http" ...@@ -86,6 +86,7 @@ name = "http"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"ctrlc", "ctrlc",
"mime",
"quinn", "quinn",
] ]
...@@ -113,6 +114,12 @@ dependencies = [ ...@@ -113,6 +114,12 @@ dependencies = [
"cfg-if", "cfg-if",
] ]
[[package]]
name = "mime"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]] [[package]]
name = "mio" name = "mio"
version = "0.8.6" version = "0.8.6"
......
...@@ -8,3 +8,4 @@ edition = "2021" ...@@ -8,3 +8,4 @@ edition = "2021"
[dependencies] [dependencies]
quinn = "0.9.3" quinn = "0.9.3"
ctrlc = "3.2.5" ctrlc = "3.2.5"
mime = "0.3.17"
...@@ -2,8 +2,11 @@ use std::{ ...@@ -2,8 +2,11 @@ use std::{
fs, fs,
io::{BufRead, BufReader, Write}, io::{BufRead, BufReader, Write},
net::TcpStream, net::TcpStream,
path::PathBuf,
}; };
use mime::Mime;
pub fn handle_connection(mut stream: TcpStream) { pub fn handle_connection(mut stream: TcpStream) {
let buf_reader = BufReader::new(&mut stream); let buf_reader = BufReader::new(&mut stream);
let http_request: Vec<_> = buf_reader let http_request: Vec<_> = buf_reader
...@@ -12,23 +15,57 @@ pub fn handle_connection(mut stream: TcpStream) { ...@@ -12,23 +15,57 @@ pub fn handle_connection(mut stream: TcpStream) {
.take_while(|line| !line.is_empty()) .take_while(|line| !line.is_empty())
.collect(); .collect();
let path_elements = http_request[0] let path = parse_request(&http_request[0]);
let status_line;
let mime_type;
let contents = if let Ok(file) = fs::read(&path) {
status_line = "HTTP/1.1 200 OK";
mime_type = find_mimetype(&path.to_str().unwrap().to_string());
file
} else {
status_line = "HTTP/1.1 404 NOT FOUND";
mime_type = find_mimetype(&"html".to_string());
fs::read("404.html").unwrap()
};
println!("{mime_type}");
let response = format!(
"{}\r\nContent-Length: {}\r\nContent-Type: {}\r\n\r\n",
status_line,
contents.len(),
mime_type
);
stream.write_all(response.as_bytes()).unwrap();
stream.write(&contents).unwrap();
}
fn parse_request(request: &str) -> PathBuf {
let path_elements = request
.split(" ") .split(" ")
.nth(1) .nth(1)
.unwrap() .unwrap()
.split("/") .split("/")
.filter(|&val| val != ".." && val != "") .filter(|&val| val != ".." && val != "")
.collect::<Vec<&str>>(); .collect::<Vec<&str>>();
let mut path = String::from("./"); PathBuf::from(format!("./{}", path_elements.join("/")))
path.push_str(&path_elements.join("/")); }
println!("{:?}", path_elements);
println!("{:?}", path);
let status_line = "HTTP/1.1 200 OK";
let contents = fs::read_to_string(path).unwrap_or(fs::read_to_string("404.html").unwrap());
let length = contents.len();
let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"); fn find_mimetype(filename: &String) -> Mime {
let parts: Vec<&str> = filename.split('.').collect();
stream.write_all(response.as_bytes()).unwrap(); let res = match parts.last() {
Some(v) => match *v {
"png" => mime::IMAGE_PNG,
"jpg" => mime::IMAGE_JPEG,
"json" => mime::APPLICATION_JSON,
"html" => mime::TEXT_HTML,
"css" => mime::TEXT_CSS,
&_ => mime::TEXT_PLAIN,
},
None => mime::TEXT_PLAIN,
};
return res;
} }
...@@ -13,20 +13,19 @@ pub struct Route { ...@@ -13,20 +13,19 @@ pub struct Route {
// handler: fn(Request) -> Outcome, // handler: fn(Request) -> Outcome,
uri: &'static str, uri: &'static str,
rank: isize, rank: isize,
format: Format, format: Option<Format>,
} }
impl Route { impl Route {
pub fn from(routeinfo: RoutInfo) -> Self { pub fn from(routeinfo: RoutInfo) -> Self {
let rank = routeinfo.rank.unwrap_or(0); let rank = routeinfo.rank.unwrap_or(0);
let format = routeinfo.format.unwrap_or(Format::Plain);
Route { Route {
name: routeinfo.name, name: routeinfo.name,
method: routeinfo.method, method: routeinfo.method,
// handler: routeinfo.handler, // handler: routeinfo.handler,
uri: routeinfo.path, uri: routeinfo.path,
rank, rank,
format, format: routeinfo.format,
} }
} }
} }
......
...@@ -86,6 +86,7 @@ name = "http" ...@@ -86,6 +86,7 @@ name = "http"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"ctrlc", "ctrlc",
"mime",
"quinn", "quinn",
] ]
...@@ -113,6 +114,12 @@ dependencies = [ ...@@ -113,6 +114,12 @@ dependencies = [
"cfg-if", "cfg-if",
] ]
[[package]]
name = "mime"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]] [[package]]
name = "mio" name = "mio"
version = "0.8.6" version = "0.8.6"
......
File moved
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment