actix-web
actix-web copied to clipboard
Consider introducing default fallback to index file in Files
Expected Behavior
I would like to have a function like default_to_index_file
for the Files service with specified index_file
. This behavior allows SPA web pages with client-side routing, so it must be pretty popular. Example:
App::new()
.service(
Files::new("/", &args.website)
.index_file(&args.index)
.default_to_index_file()
)
.bind(&args.address)?
.run
.await
Alternatively, passing a boolean as a second parameter to the index_file
:
App::new()
.service(
Files::new("/", &args.website)
.index_file(&args.index, true)
)
.bind(&args.address)?
.run
.await
Current Behavior
I had to copy-paste someone's little closure to the default_handler
. Here it is:
|req: ServiceRequest| {
let (http_req, _payload) = req.into_parts();
let ctx = http_req.app_data::<web::Data<Context>>().unwrap();
let path = format!("{}/{}", ctx.args.website, ctx.args.index);
async {
let response = NamedFile::open(path)?.into_response(&http_req)?;
Ok(ServiceResponse::new(http_req, response))
}
}
Also, since I didn't hardcode the file path — I had to pass my Args (or it could be just that path
) through the app's data, which I wouldn't do otherwise.
Context
I have tried to build a simple API + static files server for my coursework's SPA. Newbie in Rust (esp. async) and in general.
for now you can try out: https://docs.rs/actix-web-lab/0.9.0/actix_web_lab/web/struct.Spa.html
https://github.com/robjtede/actix-web-lab/blob/main/examples/spa.rs
Why not simple use this?
let ui = web::scope("/ui")
.route("/{path:[^.]*}", web::get().to(index))
.service(Files::new("/", "./static").index_file("index.html"));
Fun fact that "/path:[^.]*}" was copied from a Spring Boot project where this also worked flawlessly. Pretty cool that this solution is so portable.