refactor: cors for allow origin and headers
Diff
src/cors.rs | 6 +++---
src/handler.rs | 7 +++++--
src/static_files.rs | 26 +++++++++++++++-----------
3 files changed, 23 insertions(+), 16 deletions(-)
@@ -51,9 +51,9 @@ pub fn new(origins_str: String, headers_str: String) -> Option<Arc<Configured>>
if cors_res.is_some() {
tracing::info!(
"enabled=true, allow_headers=[{}], allow_methods=[GET,HEAD,OPTIONS], allow_origins={}",
headers_str,
origins_str
"enabled=true, allow_methods=[GET,HEAD,OPTIONS], allow_origins={}, allow_headers=[{}]",
origins_str,
headers_str
);
}
cors_res
@@ -119,8 +119,11 @@ impl RequestHandler {
Ok(mut resp) => {
if let Some(cors_headers) = cors_headers {
for (k, v) in cors_headers.iter() {
resp.headers_mut().insert(k, v.to_owned());
if !cors_headers.is_empty() {
for (k, v) in cors_headers.iter() {
resp.headers_mut().insert(k, v.to_owned());
}
resp.headers_mut().remove(http::header::ALLOW);
}
}
@@ -8,7 +8,7 @@ use headers::{
AcceptRanges, ContentLength, ContentRange, ContentType, HeaderMap, HeaderMapExt, HeaderValue,
IfModifiedSince, IfRange, IfUnmodifiedSince, LastModified, Range,
};
use http::header::{ALLOW, CONTENT_TYPE};
use http::header::CONTENT_TYPE;
use humansize::{file_size_opts, FileSize};
use hyper::{Body, Method, Response, StatusCode};
use percent_encoding::percent_decode_str;
@@ -55,16 +55,6 @@ pub async fn handle(
return Err(StatusCode::METHOD_NOT_ALLOWED);
}
if method == Method::OPTIONS {
let mut resp = Response::new(Body::empty());
*resp.status_mut() = StatusCode::NO_CONTENT;
resp.headers_mut()
.insert(ALLOW, HeaderValue::from_static("OPTIONS, GET, HEAD"));
resp.headers_mut().typed_insert(AcceptRanges::bytes());
return Ok(resp);
}
let base = Arc::new(base_path.into());
let (filepath, meta, auto_index) = path_from_tail(base, uri_path).await?;
@@ -89,6 +79,20 @@ pub async fn handle(
return Ok(resp);
}
if method == Method::OPTIONS {
let mut resp = Response::new(Body::empty());
*resp.status_mut() = StatusCode::NO_CONTENT;
resp.headers_mut()
.typed_insert(headers::Allow::from_iter(vec![
Method::OPTIONS,
Method::HEAD,
Method::GET,
]));
resp.headers_mut().typed_insert(AcceptRanges::bytes());
return Ok(resp);
}