Hacker News new | ask | show | jobs
by bpicolo 3263 days ago
Hey Sergio,

Regarding fairings, it seems a missing "middleware" case might be the sorts of things that cause redirects on entry (e.g. redirect routes with/without trailing slashes to the latter as a super trivial example). Is that something you'd expect to support in some way? I think that's something that doesn't feel like it maps either to guards or fairings well at the moment.

I did see where you mentioned your dislike of rails/sinatra/... style blunt force middleware, fwiw.

1 comments

This is actually possible with fairings! Because fairings can rewrite requests, it's possible to create a fairing that rewrites a request URI of `path/` to `path` or vice-versa as needed. Rocket will route the rewritten request normally. In psuedocode, such a fairing might look like:

  on_request => |request, _| {
      if request.uri().path().ends_with('/') {
          let new_path = request.uri().path()[..-1];
          request.set_uri(URI::new(new_path));
      }
  }
You can also use a fairing If you want to return a 302 (or similar) so that the browser does the redirect instead. In this case, you'd implement a response fairing that rewrites failed responses to return a redirect to the appropriate URI. Again, in pseudocode, this would look like:

  on_response => |request, response| {
      if response.status() == Status::NotFound && request.uri().path().ends_with('/') {
          response.set_status(Status::Found);
          response.set_header(Location(request.uri().path()[..-1]));
          response.take_body();
      }
  }
Take a look at the fairings guide [0] and fairings documentation [1] for more ideas!

[0]: https://rocket.rs/guide/fairings/

[1]: https://api.rocket.rs/rocket/fairing/trait.Fairing.html