|
| 1 | +use std::sync::OnceLock; |
| 2 | + |
| 3 | +use rocket::{ |
| 4 | + fairing::{Fairing, Info, Kind}, |
| 5 | + Data, Orbit, Request, Rocket, Route, |
| 6 | +}; |
| 7 | + |
| 8 | +// heavily inspired by rocket's `rocket::fairing::AdHoc::uri_normalizer()` implementation |
| 9 | +// only difference is that this applies a trailing slash internally as opposed to omitting it |
| 10 | +// https://api.rocket.rs/master/src/rocket/fairing/ad_hoc.rs#315 |
| 11 | +pub fn uri_normalizer() -> impl Fairing { |
| 12 | + #[derive(Default)] |
| 13 | + struct Normalizer { |
| 14 | + routes: OnceLock<Vec<Route>>, |
| 15 | + } |
| 16 | + |
| 17 | + impl Normalizer { |
| 18 | + fn routes(&self, rocket: &Rocket<Orbit>) -> &[Route] { |
| 19 | + // gather all defined routes which have a trailing slash |
| 20 | + self.routes.get_or_init(|| { |
| 21 | + rocket |
| 22 | + .routes() |
| 23 | + .filter(|r| r.uri.has_trailing_slash() || r.uri.path() == "/") |
| 24 | + .cloned() |
| 25 | + .collect() |
| 26 | + }) |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + #[rocket::async_trait] |
| 31 | + impl Fairing for Normalizer { |
| 32 | + fn info(&self) -> Info { |
| 33 | + Info { |
| 34 | + name: "URI Normalizer", |
| 35 | + kind: Kind::Liftoff | Kind::Request, |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + async fn on_liftoff(&self, rocket: &Rocket<Orbit>) { |
| 40 | + let _ = self.routes(rocket); |
| 41 | + } |
| 42 | + |
| 43 | + async fn on_request(&self, request: &mut Request<'_>, _: &mut Data<'_>) { |
| 44 | + if request.uri().has_trailing_slash() { |
| 45 | + return; |
| 46 | + } |
| 47 | + |
| 48 | + if let Some(normalized) = request.uri().map_path(|p| format!("{}/", p)) { |
| 49 | + // check if the normalized uri (the request uri with a trailing slash) matches one of our defined routes |
| 50 | + if self.routes(request.rocket()).iter().any(|r| { |
| 51 | + // we need to leverage rocket's route matching otherwise this will suck |
| 52 | + let mut normalized_req = request.clone(); |
| 53 | + normalized_req.set_uri(normalized.clone()); |
| 54 | + r.matches(&normalized_req) |
| 55 | + }) { |
| 56 | + // the request doesn't have a trailing slash AND it's trying to reach one of our defined routes |
| 57 | + // so just point it to our defined route |
| 58 | + request.set_uri(normalized); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + Normalizer::default() |
| 65 | +} |
0 commit comments