From 6d3a5ac9ba5cfc18563676380b41904968109983 Mon Sep 17 00:00:00 2001 From: _ <_@_> Date: Fri, 30 Oct 2020 17:25:22 -0500 Subject: [PATCH] :recycle: Extract serve_all func --- src/bin/relay.rs | 12 +++-- src/bin/server.rs | 121 +++++++++++++++++++--------------------------- src/http_serde.rs | 7 ++- 3 files changed, 62 insertions(+), 78 deletions(-) diff --git a/src/bin/relay.rs b/src/bin/relay.rs index 9084211..d350249 100644 --- a/src/bin/relay.rs +++ b/src/bin/relay.rs @@ -36,7 +36,7 @@ use ptth::{ enum Message { Meow, - HttpRequestResponse (http_serde::RequestParts), + HttpRequestResponse (http_serde::WrappedRequest), 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 ())) ); - http_serde::RequestParts { + http_serde::WrappedRequest { id, - method, - uri, - headers, + req: http_serde::RequestParts { + method, + uri, + headers, + }, } }; diff --git a/src/bin/server.rs b/src/bin/server.rs index a461df7..bb45c50 100644 --- a/src/bin/server.rs +++ b/src/bin/server.rs @@ -54,39 +54,6 @@ fn parse_range_header (range_str: &str) -> (Option , Option ) { 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 - ) { - 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 { let (tx, rx) = channel (2); @@ -236,37 +203,18 @@ async fn serve_error ( ) -> http_serde::Response { - let mut response = http_serde::Response::default (); - - response.status_code (status_code); - response.body (msg.into ()); - - response + let mut resp = http_serde::Response::default (); + resp.status_code (status_code) + .body (msg.into ()); + resp } -async fn handle_all ( - client: &Client, - req_resp: reqwest::Response -) -> Result <(), Box > { - //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, - _ => return Ok (()), - }; - - let (req_id, uri) = (parts.id, parts.uri); - - println! ("Client requested {}", uri); +async fn serve_all ( + parts: http_serde::RequestParts +) +-> http_serde::Response +{ + println! ("Client requested {}", parts.uri); let mut range_start = None; let mut range_end = None; @@ -286,17 +234,15 @@ async fn handle_all ( _ => false, }; - //println! ("Step 6"); - 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 mut full_path = PathBuf::from ("/home/user"); 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 } else if let Ok (file) = File::open (&full_path).await { @@ -309,14 +255,45 @@ async fn handle_all ( } else { serve_error (http_serde::StatusCode::NotFound, "404 Not Found".into ()).await + } +} + +async fn handle_req_resp ( + client: &Client, + req_resp: reqwest::Response +) -> Result <(), Box > { + //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 { - client, - req_id: &req_id, - }; + let (req_id, parts) = (wrapped_req.id, wrapped_req.req); - 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 (()) } @@ -351,7 +328,7 @@ async fn main () -> Result <(), Box > { let client = client.clone (); tokio::spawn (async move { - match handle_all (&client, req_resp).await { + match handle_req_resp (&client, req_resp).await { _ => (), } }); diff --git a/src/http_serde.rs b/src/http_serde.rs index 9197be7..1927345 100644 --- a/src/http_serde.rs +++ b/src/http_serde.rs @@ -39,7 +39,6 @@ impl TryFrom for Method { #[derive (Deserialize, Serialize)] pub struct RequestParts { - pub id: String, pub method: Method, // Technically URIs are subtle and complex but I don't care @@ -53,6 +52,12 @@ pub struct RequestParts { pub headers: HashMap >, } +#[derive (Deserialize, Serialize)] +pub struct WrappedRequest { + pub id: String, + pub req: RequestParts, +} + #[derive (Deserialize, Serialize)] pub enum StatusCode { Ok,