kilork/actix-web-static-files

Use at root - but continue to next route if none is matched

joepio opened this issue · 3 comments

Hi there,

Thanks for making and maintaining this!

I need to mount the contents of a directory that needs to be on root (robots.txt, a serviceworker.js file), but of course I also want to have other handlers as well.

If I do this, all other routes don't work - they 404. The my_custom_handler isn't called.

.service(ResourceFiles::new("", generated))
.service(web::resource(ANY).to(my_custom_handler))

Is there a way I can use actix-web-static-files in such a manner that I can only let the handler match for files that are present? In other words: can the ResourceFiles handler not return 404s, but simply skip to the next handler?

Cheers!

Edit:

Some ideas:

Currently, the respond_to function checks if there's a file found, and will either return the Item or respond with a 404. Can we respond with something that tells Actix not to use this handler further? I don't think that's how Actix is supposed to work.

Guard

Add a guard that, on init, checks the files in the target folder and only allows request processing with matching files. It might not be idiomatic, as Actix states that guards should not be used for path matching (there's other tools for that), but I don't know how we can use other path matching tools in this case. Since ResourceFiles::new takes a HashMap of files, this shouldn't be too hard. However, since ResourceFiles is a Factory, I'm not actually sure on how to add this guard from outside of this crate.

// This does not work
.service(ResourceFiles::new("/", generated).guard(my_guard)

However, we could add the guard in the register function of the HttpServicefactory impl block.

EDIT: I added the guard to the register function, that's way cleaner

Hi, thank you for your kind words!

Maybe I do not understand your use case, but library documentation suggests to place static resource route as last in the list:

https://github.com/kilork/actix-web-static-files#use-case-5-angular-like-applications

Remember to place you static resource route after all other routes in this case.

Hi kilork!

That doesn't cover my usecase, as I have another handler that catches all routes. However, that one requires DB lookups to determine if the result is a 404, while static files is way faster as it's a hashmap check.

Adding a guard is probably the right way to fix this, see my PR #55

@joepio This makes sense, thank you for explaining.

Guard will do the work, I think your patch shows this quite well. I want to play with it a little bit, because I have feeling if we allow to enable resource specific guard - we should allow actually to set custom guard as well.