Skip to content

Commit 6fe8c4c

Browse files
author
Justin Pflueger
committed
add fallback route capability
Signed-off-by: Justin Pflueger <[email protected]>
1 parent 208628b commit 6fe8c4c

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@ lint:
1212

1313
.PHONY: test-unit
1414
test-unit:
15-
RUST_LOG=$(LOG_LEVEL) cargo test --target=$$(rustc -vV | sed -n 's|host: ||p')
15+
RUST_LOG=$(LOG_LEVEL) cargo test --target=$$(rustc -vV | sed -n 's|host: ||p') -- --test-threads=1

src/lib.rs

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ const BROTLI_LEVEL: u32 = 3;
2525
const BROTLI_ENCODING: &str = "br";
2626
/// The path info header.
2727
const PATH_INFO_HEADER: &str = "spin-path-info";
28+
// Environment variable for the fallback path
29+
const FALLBACK_PATH_ENV: &str = "FALLBACK_PATH";
2830

2931
/// Common Content Encodings
3032
#[derive(Debug, Eq, PartialEq)]
@@ -77,7 +79,19 @@ fn serve(req: Request) -> Result<Response> {
7779
_ => path,
7880
};
7981

80-
let body = match FileServer::read(path, &enc) {
82+
// read from the fallback path if the variable exists
83+
let read_result = match std::env::var(FALLBACK_PATH_ENV) {
84+
Ok(fallback_path) => {
85+
println!("Fallback Path: {:?}", fallback_path);
86+
FileServer::read(path, &enc).or_else(|_| FileServer::read(fallback_path.as_str(), &enc))
87+
}
88+
Err(e) => {
89+
eprintln!("Cannot read env var: {:?}", e);
90+
FileServer::read(path, &enc)
91+
}
92+
};
93+
94+
let body = match read_result {
8195
Ok(b) => Some(b),
8296
Err(e) => {
8397
eprintln!("Cannot read file: {:?}", e);
@@ -264,6 +278,26 @@ mod tests {
264278
assert_eq!(rsp.status, 404);
265279
}
266280

281+
#[test]
282+
fn test_serve_file_not_found_with_fallback_path() {
283+
//NOTE: this test must not run in parallel to other tests because of it's use of an environment variable
284+
// hence the `--test-threads=1` in the `make test` target
285+
std::env::set_var(FALLBACK_PATH_ENV, "hello-test.txt");
286+
let req = spin_http::Request {
287+
method: spin_http::Method::Get,
288+
uri: "http://thisistest.com".to_string(),
289+
headers: vec![(
290+
PATH_INFO_HEADER.to_string(),
291+
"not-existent-file".to_string(),
292+
)],
293+
params: vec![],
294+
body: None,
295+
};
296+
let rsp = <super::SpinHttp as spin_http::SpinHttp>::handle_http_request(req);
297+
std::env::remove_var(FALLBACK_PATH_ENV);
298+
assert_eq!(rsp.status, 200);
299+
}
300+
267301
#[test]
268302
fn test_serve_index() {
269303
let req = spin_http::Request {

0 commit comments

Comments
 (0)