Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for custom 404 document #38

Merged
merged 2 commits into from
Aug 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,27 @@ value is set, the default behavior is to return a 404 Not Found response. This b
is useful for Single Page Applications that use view routers on the front-end like React and Vue.

```toml
# For more on configuring a component, see: https://spin.fermyon.dev/configuration/
# For more on configuring a component, see: https://developer.fermyon.com/spin/writing-apps#adding-environment-variables-to-components
[[component]]
source = "target/wasm32-wasi/release/spin_static_fs.wasm"
id = "fs"
files = [{ source = "test", destination = "/" }]
environment = { FALLBACK_PATH = "index.html" }
```

### Using a custom 404 document

You can configure a `CUSTOM_404_PATH` environment variable and point to a file that will be served instead of returning a plain 404 Not Found response. Consider the following sample where the `spin-fileserver` component is configured to serve all files from the `test` folder. The desired page must exist in the `test` folder to send a custom 404 HTML page (here, `404.html`) instead of a plain 404 Not Found response.

```toml
# For more on configuring a component, see: https://developer.fermyon.com/spin/writing-apps#adding-environment-variables-to-components
[[component]]
source = "target/wasm32-wasi/release/spin_static_fs.wasm"
id = "fs"
files = [{ source = "test", destination = "/" }]
environment = { CUSTOM_404_PATH = "404.html" }
```

### Building from source and using

Prerequisites:
Expand Down
64 changes: 63 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ const BROTLI_ENCODING: &str = "br";
const PATH_INFO_HEADER: &str = "spin-path-info";
// Environment variable for the fallback path
const FALLBACK_PATH_ENV: &str = "FALLBACK_PATH";
/// Environment variable for the custom 404 path
const CUSTOM_404_PATH_ENV: &str = "CUSTOM_404_PATH";
/// Directory fallback path (trying to map `/about/` -> `/about/index.html`).
const DIRECTORY_FALLBACK_PATH: &str = "index.html";

Expand Down Expand Up @@ -112,7 +114,16 @@ impl FileServer {
}
}

// return the path if it exists
if path.exists() {
return Some(path);
}

// check if user configured a custom 404 path
// if so, check if that path exists and return it instead of sending a plain 404
if let Ok(custom_404) = std::env::var(CUSTOM_404_PATH_ENV) {
path = PathBuf::from(custom_404);
}

if path.exists() {
Some(path)
} else {
Expand Down Expand Up @@ -198,6 +209,8 @@ impl FileServer {

#[cfg(test)]
mod tests {
use std::{fs, path::Path};

use http::header::{ACCEPT_ENCODING, IF_NONE_MATCH};

use super::*;
Expand Down Expand Up @@ -298,6 +311,55 @@ mod tests {
assert_eq!(rsp.status, 404);
}

#[test]
fn test_serve_custom_404() {
// reuse existing asset as custom 404 doc
let custom_404_path = "hello-test.txt";
let expected_status = 200;
let expected_body =
fs::read(Path::new(custom_404_path)).expect("Could not read custom 404 file");

std::env::set_var(CUSTOM_404_PATH_ENV, custom_404_path);

let req = spin_http::Request {
method: spin_http::Method::Get,
uri: "http://thisistest.com".to_string(),
headers: vec![(
PATH_INFO_HEADER.to_string(),
"not-existent-file".to_string(),
)],
params: vec![],
body: None,
};
let rsp = <super::SpinHttp as spin_http::SpinHttp>::handle_http_request(req);
std::env::remove_var(CUSTOM_404_PATH_ENV);
assert_eq!(rsp.status, expected_status);
assert_eq!(rsp.body, expected_body.into());
}

#[test]
fn test_serve_non_existing_custom_404() {
// provide a invalid path
let custom_404_path = "non-existing-404.html";
let expected_status = 404;

std::env::set_var(CUSTOM_404_PATH_ENV, custom_404_path);

let req = spin_http::Request {
method: spin_http::Method::Get,
uri: "http://thisistest.com".to_string(),
headers: vec![(
PATH_INFO_HEADER.to_string(),
"not-existent-file".to_string(),
)],
params: vec![],
body: None,
};
let rsp = <super::SpinHttp as spin_http::SpinHttp>::handle_http_request(req);
std::env::remove_var(CUSTOM_404_PATH_ENV);
assert_eq!(rsp.status, expected_status);
}

#[test]
fn test_serve_file_not_found_with_fallback_path() {
//NOTE: this test must not run in parallel to other tests because of it's use of an environment variable
Expand Down
Loading