use hyper::HeaderMap;
use std::path::{Path, PathBuf};
use crate::{
response::{self, error_response::internal_server_error_response, file_response::FileResponse},
types::BoxBody,
};
pub struct MiddlewareResponse {
pub file_path: String,
pub request_headers: HeaderMap,
pub confine_to: Option<PathBuf>,
pub cors_allow_credentials_origins: Vec<String>,
}
impl MiddlewareResponse {
pub fn new(
file_path: &str,
request_headers: &HeaderMap,
confine_to: Option<&Path>,
cors_allow_credentials_origins: &[String],
) -> Self {
MiddlewareResponse {
file_path: file_path.to_owned(),
request_headers: request_headers.to_owned(),
confine_to: confine_to.map(Path::to_path_buf),
cors_allow_credentials_origins: cors_allow_credentials_origins.to_vec(),
}
}
pub async fn file_response(
&self,
rhai_response_file_path: &str,
) -> Option<Result<hyper::Response<BoxBody>, hyper::http::Error>> {
let file_path = if Path::new(rhai_response_file_path).is_absolute() {
rhai_response_file_path.to_owned()
} else {
let middleware_dir_path = Path::new(self.file_path.as_str()).parent();
let joined_file_path = match middleware_dir_path {
Some(x) => x.join(rhai_response_file_path),
None => {
log::error!(
"failed to get middleware parent dir: {}",
self.file_path.as_str(),
);
return Some(internal_server_error_response(
"failed to resolve middleware response file",
&self.request_headers,
&self.cors_allow_credentials_origins,
));
}
};
match joined_file_path.to_str() {
Some(x) => x.to_owned(),
None => {
log::error!(
"middleware response file path is invalid: {}/{}",
self.file_path.as_str(),
rhai_response_file_path
);
return Some(internal_server_error_response(
"middleware response file path is invalid",
&self.request_headers,
&self.cors_allow_credentials_origins,
));
}
}
};
Some(
FileResponse::new(
file_path.as_str(),
None,
&self.request_headers,
self.confine_to.as_deref(),
&self.cors_allow_credentials_origins,
)
.file_content_response()
.await,
)
}
pub fn json_response(
&self,
json_str: &str,
) -> Option<Result<hyper::Response<BoxBody>, hyper::http::Error>> {
Some(response::json_response::json_response(
json_str,
None,
None,
&self.request_headers,
Some(self.file_path.as_str()),
&self.cors_allow_credentials_origins,
))
}
pub fn text_response(
&self,
s: &str,
) -> Option<Result<hyper::Response<BoxBody>, hyper::http::Error>> {
Some(response::text_response::text_response(
s,
None,
None,
&self.request_headers,
&self.cors_allow_credentials_origins,
))
}
}