♻️ Extract serve_all func

main
_ 2020-10-30 17:25:22 -05:00
parent 325f68b566
commit 6d3a5ac9ba
3 changed files with 62 additions and 78 deletions

View File

@ -36,7 +36,7 @@ use ptth::{
enum Message { enum Message {
Meow, Meow,
HttpRequestResponse (http_serde::RequestParts), HttpRequestResponse (http_serde::WrappedRequest),
HttpResponseResponseStream ((http_serde::ResponseParts, Body)), HttpResponseResponseStream ((http_serde::ResponseParts, Body)),
} }
@ -133,11 +133,13 @@ async fn handle_http_request (
.map (|(k, v)| (String::from (k.as_str ()), v.as_bytes ().to_vec ())) .map (|(k, v)| (String::from (k.as_str ()), v.as_bytes ().to_vec ()))
); );
http_serde::RequestParts { http_serde::WrappedRequest {
id, id,
req: http_serde::RequestParts {
method, method,
uri, uri,
headers, headers,
},
} }
}; };

View File

@ -54,39 +54,6 @@ fn parse_range_header (range_str: &str) -> (Option <u64>, Option <u64>) {
const SERVER_URL: &str = "http://127.0.0.1:4000"; const SERVER_URL: &str = "http://127.0.0.1:4000";
struct ResponseHandle <'a> {
client: &'a Client,
req_id: &'a str,
}
impl <'a> ResponseHandle <'a> {
async fn respond (
self,
resp_parts: http_serde::ResponseParts,
body: Option <Body>
) {
let mut resp_req = self.client
.post (&format! ("{}/http_response/{}", SERVER_URL, self.req_id))
.header ("X-PTTH-2LJYXWC4", base64::encode (rmp_serde::to_vec (&resp_parts).unwrap ()));
if let Some (body) = body {
resp_req = resp_req.body (body);
}
//println! ("Step 6");
if let Err (e) = resp_req.send ().await {
println! ("Err: {:?}", e);
}
}
async fn respond_2 (
self,
r: http_serde::Response
) {
self.respond (r.parts, r.body).await
}
}
async fn serve_dir (mut dir: ReadDir) -> http_serde::Response { async fn serve_dir (mut dir: ReadDir) -> http_serde::Response {
let (tx, rx) = channel (2); let (tx, rx) = channel (2);
@ -236,37 +203,18 @@ async fn serve_error (
) )
-> http_serde::Response -> http_serde::Response
{ {
let mut response = http_serde::Response::default (); let mut resp = http_serde::Response::default ();
resp.status_code (status_code)
response.status_code (status_code); .body (msg.into ());
response.body (msg.into ()); resp
response
} }
async fn handle_all ( async fn serve_all (
client: &Client, parts: http_serde::RequestParts
req_resp: reqwest::Response )
) -> Result <(), Box <dyn Error>> { -> http_serde::Response
//println! ("Step 1");
if req_resp.status () != StatusCode::OK {
// TODO: Error handling
return Ok (());
}
println! ("Step 3");
let body = req_resp.bytes ().await?;
let parts: http_serde::RequestParts = match rmp_serde::from_read_ref (&body)
{ {
Ok (x) => x, println! ("Client requested {}", parts.uri);
_ => return Ok (()),
};
let (req_id, uri) = (parts.id, parts.uri);
println! ("Client requested {}", uri);
let mut range_start = None; let mut range_start = None;
let mut range_end = None; let mut range_end = None;
@ -286,17 +234,15 @@ async fn handle_all (
_ => false, _ => false,
}; };
//println! ("Step 6");
use percent_encoding::*; use percent_encoding::*;
let encoded_path = &uri [1..]; let encoded_path = &parts.uri [1..];
let path = percent_decode (encoded_path.as_bytes ()).decode_utf8 ().unwrap (); let path = percent_decode (encoded_path.as_bytes ()).decode_utf8 ().unwrap ();
let mut full_path = PathBuf::from ("/home/user"); let mut full_path = PathBuf::from ("/home/user");
full_path.push (&*path); full_path.push (&*path);
let response = if let Ok (dir) = read_dir (&full_path).await { if let Ok (dir) = read_dir (&full_path).await {
serve_dir (dir).await serve_dir (dir).await
} }
else if let Ok (file) = File::open (&full_path).await { else if let Ok (file) = File::open (&full_path).await {
@ -309,14 +255,45 @@ async fn handle_all (
} }
else { else {
serve_error (http_serde::StatusCode::NotFound, "404 Not Found".into ()).await serve_error (http_serde::StatusCode::NotFound, "404 Not Found".into ()).await
}
}
async fn handle_req_resp (
client: &Client,
req_resp: reqwest::Response
) -> Result <(), Box <dyn Error>> {
//println! ("Step 1");
if req_resp.status () != StatusCode::OK {
// TODO: Error handling
return Ok (());
}
println! ("Step 3");
let body = req_resp.bytes ().await?;
let wrapped_req: http_serde::WrappedRequest = match rmp_serde::from_read_ref (&body)
{
Ok (x) => x,
_ => return Ok (()),
}; };
let response_handle = ResponseHandle { let (req_id, parts) = (wrapped_req.id, wrapped_req.req);
client,
req_id: &req_id,
};
response_handle.respond_2 (response).await; let response = serve_all (parts).await;
let mut resp_req = client
.post (&format! ("{}/http_response/{}", SERVER_URL, req_id))
.header ("X-PTTH-2LJYXWC4", base64::encode (rmp_serde::to_vec (&response.parts).unwrap ()));
if let Some (body) = response.body {
resp_req = resp_req.body (body);
}
//println! ("Step 6");
if let Err (e) = resp_req.send ().await {
println! ("Err: {:?}", e);
}
Ok (()) Ok (())
} }
@ -351,7 +328,7 @@ async fn main () -> Result <(), Box <dyn Error>> {
let client = client.clone (); let client = client.clone ();
tokio::spawn (async move { tokio::spawn (async move {
match handle_all (&client, req_resp).await { match handle_req_resp (&client, req_resp).await {
_ => (), _ => (),
} }
}); });

View File

@ -39,7 +39,6 @@ impl TryFrom <hyper::Method> for Method {
#[derive (Deserialize, Serialize)] #[derive (Deserialize, Serialize)]
pub struct RequestParts { pub struct RequestParts {
pub id: String,
pub method: Method, pub method: Method,
// Technically URIs are subtle and complex but I don't care // Technically URIs are subtle and complex but I don't care
@ -53,6 +52,12 @@ pub struct RequestParts {
pub headers: HashMap <String, Vec <u8>>, pub headers: HashMap <String, Vec <u8>>,
} }
#[derive (Deserialize, Serialize)]
pub struct WrappedRequest {
pub id: String,
pub req: RequestParts,
}
#[derive (Deserialize, Serialize)] #[derive (Deserialize, Serialize)]
pub enum StatusCode { pub enum StatusCode {
Ok, Ok,