@@ -25,6 +25,8 @@ const BROTLI_LEVEL: u32 = 3;
2525const BROTLI_ENCODING : & str = "br" ;
2626/// The path info header.
2727const 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