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

Change Status to be an enum

parent 8d669447
No related branches found
No related tags found
1 merge request!1Initial feature merge
...@@ -70,7 +70,7 @@ pub fn handle_connection(mut stream: TcpStream, mountpoints: Vec<MountPoint>) { ...@@ -70,7 +70,7 @@ pub fn handle_connection(mut stream: TcpStream, mountpoints: Vec<MountPoint>) {
let mut buffer: Vec<u8> = vec![0; length]; let mut buffer: Vec<u8> = vec![0; length];
let read_len = buf_reader.read(&mut buffer).unwrap(); let read_len = buf_reader.read(&mut buffer).unwrap();
if read_len != length { if read_len != length {
let respone = len_not_defined(Status { code: 411 }); let respone = len_not_defined(Status::LengthRequired);
stream.write_all(respone.0.as_bytes()).unwrap(); stream.write_all(respone.0.as_bytes()).unwrap();
stream.write(&respone.1).unwrap(); stream.write(&respone.1).unwrap();
return; return;
...@@ -105,15 +105,15 @@ pub fn handle_connection(mut stream: TcpStream, mountpoints: Vec<MountPoint>) { ...@@ -105,15 +105,15 @@ pub fn handle_connection(mut stream: TcpStream, mountpoints: Vec<MountPoint>) {
let response = match handled_response { let response = match handled_response {
Some(val) => match val { Some(val) => match val {
Outcome::Success(success) => ( Outcome::Success(success) => (
format!("HTTP/1.1 {} OK\r\n", success.status.unwrap().code) format!("HTTP/1.1 {}\r\n", success.status.unwrap())
+ &success.headers.join("\r\n") + &success.headers.join("\r\n")
+ "\r\n\r\n", + "\r\n\r\n",
success.body.get_data(), success.body.get_data(),
), ),
Outcome::Failure(error) => failure_handler(error), Outcome::Failure(error) => failure_handler(error),
Outcome::Forward(_) => failure_handler(Status { code: 404 }), Outcome::Forward(_) => failure_handler(Status::NotFound),
}, },
None => failure_handler(Status { code: 404 }), None => failure_handler(Status::NotFound),
}; };
stream.write_all(response.0.as_bytes()).unwrap(); stream.write_all(response.0.as_bytes()).unwrap();
...@@ -124,8 +124,8 @@ fn failure_handler(status: Status) -> (String, Vec<u8>) { ...@@ -124,8 +124,8 @@ 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 {}\r\nContent-Length: {}\r\nContent-Type: {}\r\n\r\n",
status.code, status,
page_404.get_len(), page_404.get_len(),
page_404.get_mime() page_404.get_mime()
), ),
......
...@@ -32,7 +32,7 @@ impl NamedFile { ...@@ -32,7 +32,7 @@ impl NamedFile {
let data = match data { let data = match data {
Ok(dat) => dat, Ok(dat) => dat,
Err(_) => { Err(_) => {
return Err(Status { code: 404 }); return Err(Status::NotFound);
} }
}; };
Ok(NamedFile { Ok(NamedFile {
......
use std::fmt::Display; use std::{fmt::Display, fs::write};
use mime::Mime; use mime::Mime;
...@@ -67,101 +67,146 @@ pub struct Response { ...@@ -67,101 +67,146 @@ pub struct Response {
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Status { pub enum Status {
pub code: u16, Continue,
SwitchingProtocols,
WebDavProcessing,
ExperimentalEarlyHints,
Ok,
Created,
Accepted,
NonAuthorativeIfnormation,
NoContent,
ResetContent,
PartialContent,
WebDavMultiStatus,
WebDavAlreadyReported,
HttpDataEncodingImUsed,
MultipleChoices,
MovedPermanently,
Found,
SeeOther,
NotModfiied,
DeprecatedUseProxy,
UnusedUnused,
TemporaryRedirect,
PermanentRedirect,
BadRequest,
Unauthorized,
ExperimentalPaymentRequired,
Forbidden,
NotFound,
MethodNotAllowed,
NotAcceptable,
ProxyAuthenticationRequired,
RequestTimeout,
Conflict,
Gone,
LengthRequired,
PreconditionFailed,
PayloadTooLarge,
UriTooLong,
UnsupportedMediaType,
RangeNotSatisfiable,
ExpectationFailed,
ImATeapot,
MisdirectedRequest,
WebDavUnprocessableContent,
WebDavLocked,
WebDavFailedDependency,
ExperimenalTooEarly,
UpgradeRequred,
PreconditionRequired,
TooManyRequests,
RequestHeaderFieldsTooLarge,
UnavailableForLegalReasons,
InternalServerError,
NotImplemented,
BadGetaway,
ServiceUnavailable,
GetawayTimeout,
HttpVersionNotSupported,
VariantAlsoNegotiates,
WebDavInsufficientStorage,
WebDavLoopDetected,
NotExtended,
NetworkAuthenticationRequired,
} }
impl Display for Status { impl Display for Status {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.code { match self {
// INFORMATIONAL RESPONSE Status::Continue => write!(f, "100 Continue"),
100 => write!(f, "{} Continue", self.code), Status::SwitchingProtocols => write!(f, "101 Switching Protocols"),
101 => write!(f, "{} Switching Protocols", self.code), Status::WebDavProcessing => write!(f, "102 Processing"),
Status::ExperimentalEarlyHints => write!(f, "103 Early Hints"),
// WebDAV Status::Ok => write!(f, "200 OK"),
102 => write!(f, "{} Processing", self.code), Status::Created => write!(f, "201 Created"),
Status::Accepted => write!(f, "202 Accepted"),
// Experimental Status::NonAuthorativeIfnormation => write!(f, "203 Non-Authorative Information"),
103 => write!(f, "{} Early Hints", self.code), Status::NoContent => write!(f, "204 No Content"),
Status::ResetContent => write!(f, "205 Reset Content"),
// SUCCESSFUL RESPONSE Status::PartialContent => write!(f, "206 Partial Content"),
200 => write!(f, "{} OK", self.code), Status::WebDavMultiStatus => write!(f, "207 Mutli-Status"),
201 => write!(f, "{} Created", self.code), Status::WebDavAlreadyReported => write!(f, "208 Already Reported"),
203 => write!(f, "{} Non-Authorative Information", self.code), Status::HttpDataEncodingImUsed => write!(f, "226 IM Used"),
204 => write!(f, "{} No Content", self.code), Status::MultipleChoices => write!(f, "300 Multiple Choices"),
205 => write!(f, "{} Reset Content", self.code), Status::MovedPermanently => write!(f, "301 Moved Permanently"),
206 => write!(f, "{} Partial Content", self.code), Status::Found => write!(f, "302 Found"),
Status::SeeOther => write!(f, "303 See Other"),
// WebDAV Status::NotModfiied => write!(f, "304 Not Modified"),
207 => write!(f, "{} Mutli-Status", self.code), Status::TemporaryRedirect => write!(f, "307 Temporary Redirect"),
208 => write!(f, "{} Already Reported", self.code), Status::PermanentRedirect => write!(f, "308 Permanent Redirect"),
Status::DeprecatedUseProxy => write!(f, "305 Use Proxy"),
// HTTP Delta Encoding Status::UnusedUnused => write!(f, "306 unused"),
226 => write!(f, "{} IM Used", self.code), Status::BadRequest => write!(f, "400 Bad Request"),
Status::Unauthorized => write!(f, "401 Unauthorized"),
// REDIRECTION MESSAGES Status::ExperimentalPaymentRequired => write!(f, "402 Payment Required"),
300 => write!(f, "{} Multiple Choices", self.code), Status::Forbidden => write!(f, "403 Forbidden"),
301 => write!(f, "{} Moved Permanently", self.code), Status::NotFound => write!(f, "404 Not Found"),
302 => write!(f, "{} Found", self.code), Status::MethodNotAllowed => write!(f, "405 Method Not Allowed"),
303 => write!(f, "{} See Other", self.code), Status::NotAcceptable => write!(f, "406 Not Acceptable"),
304 => write!(f, "{} Not Modified", self.code), Status::ProxyAuthenticationRequired => {
307 => write!(f, "{} Temporary Redirect", self.code), write!(f, "407 Proxy Athentication Required")
308 => write!(f, "{} Permanent Redirect", self.code), }
Status::RequestTimeout => write!(f, "408 Request Timout"),
// Unused / Deprecated Status::Conflict => write!(f, "409 Conflict"),
305 => write!(f, "{} Use Proxy", self.code), Status::Gone => write!(f, "410 Gone"),
306 => write!(f, "{} unused", self.code), Status::LengthRequired => write!(f, "411 Length Required"),
Status::PreconditionFailed => write!(f, "412 Precondition Failed"),
// CLIENT ERROR Status::PayloadTooLarge => write!(f, "413 Payload Too Large"),
400 => write!(f, "{} Bad Request", self.code), Status::UriTooLong => write!(f, "414 URI Too Long"),
401 => write!(f, "{} Unauthorized", self.code), Status::UnsupportedMediaType => write!(f, "415 Unsupported Media Type"),
403 => write!(f, "{} Forbidden", self.code), Status::RangeNotSatisfiable => write!(f, "416 Range Not Satisfiable"),
404 => write!(f, "{} Not Found", self.code), Status::ExpectationFailed => write!(f, "417 Expectation Failed"),
405 => write!(f, "{} Method Not Allowed", self.code), Status::ImATeapot => write!(f, "418 I'm a Teapot"),
406 => write!(f, "{} Not Acceptable", self.code), Status::MisdirectedRequest => write!(f, "421 Misdirected Request"),
407 => write!(f, "{} Proxy Athentication Required", self.code), Status::WebDavUnprocessableContent => write!(f, "422 Unprocessable Content"),
408 => write!(f, "{} Request Timout", self.code), Status::WebDavLocked => write!(f, "423 Locked"),
409 => write!(f, "{} Conflict", self.code), Status::WebDavFailedDependency => write!(f, "424 Failed Dependency"),
410 => write!(f, "{} Gone", self.code), Status::ExperimenalTooEarly => write!(f, "425 Too Early"),
411 => write!(f, "{} Length Required", self.code), Status::UpgradeRequred => write!(f, "426 Upgrade Required"),
412 => write!(f, "{} Precondition Failed", self.code), Status::PreconditionRequired => write!(f, "428 Precondition Required"),
413 => write!(f, "{} Payload Too Large", self.code), Status::TooManyRequests => write!(f, "429 Too Many Requests"),
414 => write!(f, "{} URI Too Long", self.code), Status::RequestHeaderFieldsTooLarge => {
415 => write!(f, "{} Unsupported Media Type", self.code), write!(f, "431 Request Header Fields Too Large")
416 => write!(f, "{} Range Not Satisfiable", self.code), }
417 => write!(f, "{} Expectation Failed", self.code), Status::UnavailableForLegalReasons => {
418 => write!(f, "{} I'm a Teapot", self.code), write!(f, "451 Unavailable For Legal Reasons")
421 => write!(f, "{} Misdirected Request", self.code), }
422 => write!(f, "{} Unprocessable Content", self.code), Status::InternalServerError => write!(f, "500 Internal Server Error"),
426 => write!(f, "{} Upgrade Required", self.code), Status::NotImplemented => write!(f, "501 Not Implmenented"),
428 => write!(f, "{} Precondition Required", self.code), Status::BadGetaway => write!(f, "502 Bad Getaway"),
429 => write!(f, "{} Too Many Requests", self.code), Status::ServiceUnavailable => write!(f, "503 Service Unavailable"),
431 => write!(f, "{} Request Header Fields Too Large", self.code), Status::GetawayTimeout => write!(f, "504 Getaway Timeout"),
Status::HttpVersionNotSupported => write!(f, "505 HTTP Version Not Supported"),
451 => write!(f, "{} Unavailable For Legal Reasons", self.code), Status::VariantAlsoNegotiates => write!(f, "506 Variant Also Negotiates"),
Status::WebDavInsufficientStorage => write!(f, "507 Insufficient Storage"),
// WebDAV Status::WebDavLoopDetected => write!(f, "508 Loop Detected"),
423 => write!(f, "{} Locked", self.code), Status::NotExtended => write!(f, "510 Not Extendend"),
424 => write!(f, "{} Failed Dependency", self.code), Status::NetworkAuthenticationRequired => {
write!(f, "511 Network Authentication Required")
// Experimental / Not in use }
402 => write!(f, "{} Payment Required", self.code),
425 => write!(f, "{} Too Early", self.code),
// SERVER ERROR RESPONSES
500 => write!(f, "{} Internal Server Error", self.code),
501 => write!(f, "{} Not Implmenented", self.code),
502 => write!(f, "{} Bad Getaway", self.code),
503 => write!(f, "{} Service Unavailable", self.code),
504 => write!(f, "{} Getaway Timeout", self.code),
505 => write!(f, "{} HTTP Version Not Supported", self.code),
506 => write!(f, "{} Variant Also Negotiates", self.code),
507 => write!(f, "{} Insufficient Storage", self.code),
508 => write!(f, "{} Loop Detected", self.code),
510 => write!(f, "{} Not Extendend", self.code),
511 => write!(f, "{} Network Authentication Required", self.code),
_ => write!(f, "500 "),
} }
} }
} }
...@@ -16,10 +16,10 @@ fn handler(request: Request, _data: Data) -> Outcome<Response, Status, Data> { ...@@ -16,10 +16,10 @@ fn handler(request: Request, _data: Data) -> Outcome<Response, Status, Data> {
format!("Content-Length: {}", dat.get_len()), format!("Content-Length: {}", dat.get_len()),
format!("Content-Type: {}", dat.get_mime()), format!("Content-Type: {}", dat.get_mime()),
], ],
status: Some(Status { code: 200 }), status: Some(Status::Ok),
body: Box::new(dat), body: Box::new(dat),
}, },
Err(_) => return Outcome::Failure(Status { code: 404 }), Err(_) => return Outcome::Failure(Status::NotFound),
}; };
Outcome::Success(response) Outcome::Success(response)
} }
......
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