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

Refactoring a lot of stuff

parent a6ffcabd
No related branches found
No related tags found
1 merge request!1Initial feature merge
...@@ -4,11 +4,14 @@ use std::{ ...@@ -4,11 +4,14 @@ use std::{
path::PathBuf, path::PathBuf,
}; };
use crate::routing::routes::{Data, Outcome, Request, Response, Status}; use crate::handling::{
file_handlers::NamedFile,
request::Request,
response::{Outcome, Response, ResponseBody, Status},
routes::Data,
};
use crate::setup::MountPoint; use crate::setup::MountPoint;
use super::file_handlers::NamedFile;
pub fn handle_connection(mut stream: TcpStream, mountpoints: Vec<MountPoint>) { pub fn handle_connection(mut stream: TcpStream, mountpoints: Vec<MountPoint>) {
let buf_reader = BufReader::new(&mut stream); let buf_reader = BufReader::new(&mut stream);
let http_request: Vec<String> = buf_reader let http_request: Vec<String> = buf_reader
...@@ -40,17 +43,14 @@ pub fn handle_connection(mut stream: TcpStream, mountpoints: Vec<MountPoint>) { ...@@ -40,17 +43,14 @@ pub fn handle_connection(mut stream: TcpStream, mountpoints: Vec<MountPoint>) {
let mut handled_response: Option<Outcome<Response, Status, Data>> = None; let mut handled_response: Option<Outcome<Response, Status, Data>> = None;
for mountpoint in mountpoints { for mountpoint in mountpoints {
if !request.uri.starts_with(mountpoint.mountpoint) { if !request.uri.starts_with(mountpoint.mountpoint) {
println!("MOUNTPOINT COMPARISON {}", request.uri);
continue; continue;
} }
let mounted_request_uri = request.uri.strip_prefix(mountpoint.mountpoint).unwrap(); let mounted_request_uri = request.uri.strip_prefix(mountpoint.mountpoint).unwrap();
for route in mountpoint.routes { for route in mountpoint.routes {
if route.method != request.method { if route.method != request.method {
println!("METHOD COMPARE {}", request.method);
continue; continue;
} }
if !route.compare_uri(mounted_request_uri) { if !route.compare_uri(mounted_request_uri) {
println!("URI COMPARISON {} {}", mounted_request_uri, route.uri);
continue; continue;
} }
handled_response = Some((route.handler)( handled_response = Some((route.handler)(
...@@ -71,23 +71,25 @@ pub fn handle_connection(mut stream: TcpStream, mountpoints: Vec<MountPoint>) { ...@@ -71,23 +71,25 @@ pub fn handle_connection(mut stream: TcpStream, mountpoints: Vec<MountPoint>) {
+ "\r\n\r\n", + "\r\n\r\n",
success.body.get_data(), success.body.get_data(),
), ),
Outcome::Failure(error) => handler_404(error), Outcome::Failure(error) => failure_handler(error),
Outcome::Forward(_) => handler_404(Status { code: 404 }), Outcome::Forward(_) => failure_handler(Status { code: 404 }),
}, },
None => handler_404(Status { code: 404 }), None => failure_handler(Status { code: 404 }),
}; };
stream.write_all(response.0.as_bytes()).unwrap(); stream.write_all(response.0.as_bytes()).unwrap();
stream.write(&response.1).unwrap(); stream.write(&response.1).unwrap();
} }
fn handler_404(status: Status) -> (String, Vec<u8>) { fn failure_handler(status: Status) -> (String, Vec<u8>) {
let page_404 = NamedFile::open(PathBuf::from("404.html")).unwrap(); let page_404 = NamedFile::open(PathBuf::from("404.html")).unwrap();
( (
format!( format!(
"HTTP/1.1 {} NOT FOUND\r\nContent-Length: {}\r\nContent-Type: {}\r\n\r\n", "HTTP/1.1 {} NOT FOUND\r\nContent-Length: {}\r\nContent-Type: {}\r\n\r\n",
status.code, page_404.content_len, page_404.content_type status.code,
page_404.get_len(),
page_404.get_mime()
), ),
page_404.content, page_404.get_data(),
) )
} }
pub mod file_handlers;
pub mod handlers; pub mod handlers;
...@@ -2,7 +2,7 @@ use std::{fs, path::PathBuf}; ...@@ -2,7 +2,7 @@ use std::{fs, path::PathBuf};
use mime::Mime; use mime::Mime;
use crate::routing::routes::{ResponseBody, Status}; use crate::handling::response::{ResponseBody, Status};
#[derive(Debug)] #[derive(Debug)]
pub struct NamedFile { pub struct NamedFile {
...@@ -15,6 +15,14 @@ impl ResponseBody for NamedFile { ...@@ -15,6 +15,14 @@ impl ResponseBody for NamedFile {
fn get_data(&self) -> Vec<u8> { fn get_data(&self) -> Vec<u8> {
self.content.clone() self.content.clone()
} }
fn get_mime(&self) -> Mime {
self.content_type.clone()
}
fn get_len(&self) -> usize {
self.content_len
}
} }
impl NamedFile { impl NamedFile {
......
pub mod file_handlers;
pub mod methods; pub mod methods;
pub mod request;
pub mod response;
pub mod routes; pub mod routes;
use std::net::SocketAddr;
use super::{methods::Method, routes::Uri};
type HeaderMap = Vec<String>;
#[derive(Clone)]
pub struct Request<'a> {
pub uri: Uri<'a>,
pub headers: HeaderMap,
pub method: Method,
// pub connection: ConnectionMeta,
}
struct ConnectionMeta {
remote: Option<SocketAddr>,
// certificates
}
#[derive(Clone, Debug, Copy)]
pub enum MediaType {
Json,
Plain,
Html,
}
use mime::Mime;
use super::routes::Body;
type HeaderMap = Vec<String>;
#[derive(Debug)]
pub enum Outcome<S, E, F> {
Success(S),
Failure(E),
Forward(F),
}
pub trait ResponseBody {
fn get_data(&self) -> Vec<u8>;
fn get_mime(&self) -> Mime;
fn get_len(&self) -> usize;
}
impl ResponseBody for Body {
fn get_data(&self) -> Vec<u8> {
self.body.clone()
}
fn get_mime(&self) -> Mime {
mime::TEXT_PLAIN
}
fn get_len(&self) -> usize {
self.get_data().len()
}
}
impl ResponseBody for &str {
fn get_data(&self) -> Vec<u8> {
self.as_bytes().to_vec()
}
fn get_mime(&self) -> Mime {
mime::TEXT_PLAIN
}
fn get_len(&self) -> usize {
self.len()
}
}
impl ResponseBody for String {
fn get_data(&self) -> Vec<u8> {
self.as_bytes().to_vec()
}
fn get_mime(&self) -> Mime {
mime::TEXT_PLAIN
}
fn get_len(&self) -> usize {
self.len()
}
}
pub struct Response {
pub headers: HeaderMap,
pub status: Option<Status>,
pub body: Box<dyn ResponseBody>,
}
#[derive(Debug)]
pub struct Status {
pub code: u16,
}
use std::net::SocketAddr; use super::{
methods::Method,
use super::methods::Method; request::{MediaType, Request},
response::{Outcome, Response, Status},
pub trait ResponseBody { };
fn get_data(&self) -> Vec<u8>;
}
pub struct RoutInfo { pub struct RoutInfo {
name: Option<&'static str>, name: Option<&'static str>,
...@@ -55,63 +53,17 @@ impl Route<'_> { ...@@ -55,63 +53,17 @@ impl Route<'_> {
return false; return false;
} }
} }
return true; true
} }
} }
#[derive(Clone)]
pub struct Request<'a> {
pub uri: Uri<'a>,
pub headers: HeaderMap,
pub method: Method,
// pub connection: ConnectionMeta,
}
struct ConnectionMeta {
remote: Option<SocketAddr>,
// certificates
}
type HeaderMap = Vec<String>;
pub type Uri<'a> = &'a str; pub type Uri<'a> = &'a str;
#[derive(Debug)] #[derive(Debug, Clone)]
pub enum Outcome<S, E, F> {
Success(S),
Failure(E),
Forward(F),
}
#[derive(Clone, Debug, Copy)]
pub enum MediaType {
Json,
Plain,
Html,
}
#[derive(Debug)]
pub struct Status {
pub code: u16,
}
#[derive(Debug)]
pub struct Body { pub struct Body {
pub size: Option<usize>,
pub body: Vec<u8>, pub body: Vec<u8>,
} }
impl ResponseBody for Body {
fn get_data(&self) -> Vec<u8> {
self.body.clone()
}
}
pub struct Response {
pub headers: HeaderMap,
pub status: Option<Status>,
pub body: Box<dyn ResponseBody>,
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Data { pub struct Data {
pub buffer: Vec<u8>, pub buffer: Vec<u8>,
......
pub mod handlers; pub mod handlers;
pub mod routing; pub mod handling;
mod setup; mod setup;
mod threading; mod threading;
......
...@@ -9,7 +9,7 @@ use std::{ ...@@ -9,7 +9,7 @@ use std::{
use crate::{ use crate::{
handlers::handlers::handle_connection, handlers::handlers::handle_connection,
routing::routes::{Route, Uri}, handling::routes::{Route, Uri},
threading::ThreadPool, threading::ThreadPool,
}; };
......
...@@ -11,6 +11,9 @@ ...@@ -11,6 +11,9 @@
<label for="message">Enter your message:</label> <label for="message">Enter your message:</label>
<input type="text" id="message" name="message" /> <input type="text" id="message" name="message" />
<button type="submit">Send</button> <button type="submit">Send</button>
<label for="message">Enter your message:</label>
<input type="text" id="asdf" name="message" />
<button type="submit">Send</button>
</form> </form>
</body> </body>
</html> </html>
use std::path::PathBuf; use std::path::PathBuf;
use http::{ use http::handling::{
handlers::file_handlers::NamedFile, file_handlers::NamedFile,
routing::routes::{Data, Outcome, Request, Response, Route, Status}, methods::Method,
request::Request,
response::{Outcome, Response, ResponseBody, Status},
routes::{Data, Route},
}; };
fn handler(request: Request, _data: Data) -> Outcome<Response, Status, Data> { fn handler(request: Request, _data: Data) -> Outcome<Response, Status, Data> {
println!("called");
let response = fileserver(request.uri.strip_prefix("static/").unwrap()); let response = fileserver(request.uri.strip_prefix("static/").unwrap());
let response = match response { let response = match response {
Ok(dat) => Response { Ok(dat) => Response {
headers: vec![ headers: vec![
format!("Content-Length: {}", dat.content_len), format!("Content-Length: {}", dat.get_len()),
format!("Content-Type: {}", dat.content_type), format!("Content-Type: {}", dat.get_mime()),
], ],
status: Some(Status { code: 200 }), status: Some(Status { code: 200 }),
body: Box::new(dat), body: Box::new(dat),
}, },
Err(_) => return Outcome::Failure(Status { code: 404 }), Err(_) => return Outcome::Failure(Status { code: 404 }),
}; };
println!("{:?}", response.headers);
Outcome::Success(response) Outcome::Success(response)
} }
fn fileserver(path: &str) -> Result<NamedFile, Status> { fn fileserver(path: &str) -> Result<NamedFile, Status> {
let file = NamedFile::open(PathBuf::from("static/".to_string() + path)); NamedFile::open(PathBuf::from("static/".to_string() + path))
return file;
} }
fn main() { fn main() {
...@@ -34,7 +34,7 @@ fn main() { ...@@ -34,7 +34,7 @@ fn main() {
handler, handler,
name: Some("file_server"), name: Some("file_server"),
uri: "static/<path..>", uri: "static/<path..>",
method: http::routing::methods::Method::Get, method: Method::Get,
rank: 0, rank: 0,
}; };
......
body {
background-color: #212121;
color: #ffffff;
}
...@@ -2,6 +2,11 @@ ...@@ -2,6 +2,11 @@
<html> <html>
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<title>JE</title> <title>Hello</title>
<link rel="stylesheet" href="/static/hello.css" />
</head> </head>
<body>
<h1>Managed</h1>
<img src="/static/img.jpg" alt="" />
</body>
</html> </html>
site/static/img.jpg

50.3 KiB

tree.txt 0 → 100644
.
├── core
│ ├── codegen
│ │ ├── Cargo.lock
│ │ ├── Cargo.toml
│ │ ├── src
│ │ │ └── lib.rs
│ ├── html
│ │ ├── Cargo.lock
│ │ ├── Cargo.toml
│ │ └── src
│ │ └── lib.rs
│ └── http
│ ├── Cargo.lock
│ ├── Cargo.toml
│ └── src
│ ├── handlers
│ │ ├── file_handlers.rs
│ │ ├── handlers.rs
│ │ └── mod.rs
│ ├── lib.rs
│ ├── routing
│ │ ├── methods.rs
│ │ ├── mod.rs
│ │ └── routes.rs
│ ├── setup.rs
│ ├── threading.rs
│ └── utils
│ └── mod.rs
├── README.md
├── site
│ ├── 404.html
│ ├── Cargo.lock
│ ├── Cargo.toml
│ ├── hello.css
│ ├── img.jpg
│ ├── src
│ │ └── main.rs
│ ├── static
│ │ └── hello.html
│ └── target
│ └── CACHEDIR.TAG
└── tree.txt
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment