♻️ 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 {
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,
},
}
};

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";
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 {
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 <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 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 <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 {
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 <dyn Error>> {
let client = client.clone ();
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)]
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 <String, Vec <u8>>,
}
#[derive (Deserialize, Serialize)]
pub struct WrappedRequest {
pub id: String,
pub req: RequestParts,
}
#[derive (Deserialize, Serialize)]
pub enum StatusCode {
Ok,