From fddab1780c909cf77faef37922aa20af905406bd Mon Sep 17 00:00:00 2001 From: rhysd Date: Fri, 2 Feb 2024 18:06:49 +0900 Subject: [PATCH] fix loading empty contents returns 404 response --- v2/src/assets.rs | 8 ++++---- v2/src/wry/webview.rs | 19 ++++++------------- 2 files changed, 10 insertions(+), 17 deletions(-) diff --git a/v2/src/assets.rs b/v2/src/assets.rs index f48ccb6..5056f21 100644 --- a/v2/src/assets.rs +++ b/v2/src/assets.rs @@ -184,7 +184,7 @@ impl Assets { Self { hljs_css, markdown_css } } - pub fn load(&self, path: &str) -> (Cow<'static, [u8]>, &'static str) { + pub fn load(&self, path: &str) -> (Option>, &'static str) { let mime = guess_mime(path); #[rustfmt::skip] @@ -198,19 +198,19 @@ impl Assets { #[cfg(debug_assertions)] "/bundle.js.map" => BUNDLE_JS_MAP.into(), #[cfg(target_os = "windows")] - "/favicon.ico" => Cow::Owned(vec![]), + "/favicon.ico" => return (None, mime), path => { log::debug!("Dynamically loading external resource {:?}", path); match fs::read(path) { Ok(content) => content.into(), Err(err) => { log::error!("Could not read external resource {:?}: {}", path, err); - Cow::Owned(vec![]) + return (None, mime); } } } }; - (body, mime) + (Some(body), mime) } } diff --git a/v2/src/wry/webview.rs b/v2/src/wry/webview.rs index 9b32dce..2f29306 100644 --- a/v2/src/wry/webview.rs +++ b/v2/src/wry/webview.rs @@ -106,7 +106,7 @@ fn create_webview(window: &Window, event_loop: &EventLoop, config: &Config) -> R log::debug!("Opening local path {:?}", path); UserEvent::OpenLocalPath(path) } else { - log::debug!("Navigating to URL {:?}", url); + log::debug!("Navigating to external URL {:?}", url); UserEvent::OpenExternalLink(url) }; @@ -124,18 +124,11 @@ fn create_webview(window: &Window, event_loop: &EventLoop, config: &Config) -> R let uri = request.uri(); log::debug!("Handling custom protocol: {:?}", uri); let path = uri.path(); - let (body, mime) = loader.load(path); - let status = if body.is_empty() { 404 } else { 200 }; - Response::builder().status(status).header(CONTENT_TYPE, mime).body(body).unwrap_or_else( - |err| { - log::error!("Could not build response for request {:?}: {:?}", uri, err); - Response::builder() - .status(404) - .header(CONTENT_TYPE, "application/octet-stream") - .body(vec![].into()) - .unwrap() - }, - ) + let (content, mime) = loader.load(path); + let (body, status) = + if let Some(content) = content { (content, 200) } else { (vec![].into(), 404) }; + // The header and status are never invalid so `.unwrap()` call never panics + Response::builder().status(status).header(CONTENT_TYPE, mime).body(body).unwrap() }) .with_web_context(&mut context) .with_focused(true)