Hacker News new | ask | show | jobs
by sbenitez 3267 days ago
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