Skip to content

Commit

Permalink
Improve response wrappers
Browse files Browse the repository at this point in the history
  • Loading branch information
WilliamRagstad committed Oct 14, 2023
1 parent d16805a commit fda947d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
20 changes: 19 additions & 1 deletion src/engine/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,22 @@ pub fn serialize_response<D: Default + ToString>(response: &Response<D>) -> Stri
result.push_str("\r\n");
result.push_str(&response.body().to_string());
result
}
}

pub mod Responses {
pub fn ok_html(body: String) -> http::Response<String> {
http::Response::builder()
.status(http::StatusCode::OK)
.header("Access-Control-Allow-Origin", "*")
.header("Content-Type", "text/html; charset=utf-8")
.header("Content-Length", body.len().to_string())
.header("Connection", "close")
.header("Server", "webx")
.header("Date", chrono::Utc::now().to_rfc2822())
.header("Cache-Control", "no-cache")
.header("Pragma", "no-cache")
.header("Expires", "0")
.body(body)
.unwrap()
}
}
5 changes: 2 additions & 3 deletions src/engine/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use http::{Response, response};

use crate::{file::webx::{WXModule, WXModulePath, WXRouteMethod, WXUrlPath, WXBody, WXRoute, WXROUTE_METHODS}, runner::WXMode, reporting::{debug::info, warning::warning, error::{error_code, ERROR_DUPLICATE_ROUTE}}, analysis::routes::{extract_flat_routes, extract_duplicate_routes, analyse_duplicate_routes, verify_model_routes}};

use super::http::{parse_request, parse_request_tcp, serialize_response};
use super::http::{parse_request, parse_request_tcp, serialize_response, Responses::ok_html};

/// A runtime error.
pub struct WXRuntimeError {
Expand Down Expand Up @@ -186,12 +186,11 @@ impl WXRuntime {
fn handle_request(&self, mut stream: TcpStream, addr: SocketAddr) {
if let Some(request) = parse_request_tcp::<()>(&stream) {
info(self.mode, &format!("(Runtime) Request from: {}\n{:#?}", stream.peer_addr().unwrap(), &request));
let response = Response::builder().status(200).body("Hello, world!").unwrap();
let response = ok_html("Hello, world!".into());
stream.write(serialize_response(&response).as_bytes()).unwrap();
info(self.mode, &format!("(Runtime) Response to: {}\n{:#?}", stream.peer_addr().unwrap(), &response));
} else {
warning(format!("(Runtime) Request read failure: {}", addr));
}
}
}

0 comments on commit fda947d

Please sign in to comment.