Skip to content

Commit 2678506

Browse files
pietroalbiniJoshua Nelson
authored andcommitted
web: add /crate/:name/:version/source redirect
1 parent 3a6d604 commit 2678506

File tree

1 file changed

+30
-11
lines changed

1 file changed

+30
-11
lines changed

src/web/routes.rs

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,10 @@ pub(super) fn build_routes() -> Routes {
7070
"/crate/:name/:version/builds/:id",
7171
super::builds::build_list_handler,
7272
);
73+
routes.internal_page(
74+
"/crate/:name/:version/source",
75+
SimpleRedirect::new(|url| url.set_path(&format!("{}/", url.path()))),
76+
);
7377
routes.internal_page(
7478
"/crate/:name/:version/source/",
7579
super::source::source_browser_handler,
@@ -180,8 +184,12 @@ impl Routes {
180184
// Automatically add another route ending with / that redirects to the slash-less route.
181185
if !pattern.ends_with('/') {
182186
let pattern = format!("{}/", pattern);
183-
self.get
184-
.push((pattern.to_string(), Box::new(remove_slashes)));
187+
self.get.push((
188+
pattern.to_string(),
189+
Box::new(SimpleRedirect::new(|url| {
190+
url.set_path(&url.path().trim_end_matches('/').to_string())
191+
})),
192+
));
185193
}
186194

187195
// Register the prefix if it's not the home page and the first path component is not a
@@ -204,15 +212,26 @@ impl Routes {
204212
}
205213
}
206214

207-
/// Simple Iron route that redirects to the same path without the trailing slash, for example
208-
/// /foo/bar/baz/ to /foo/bar/baz.
209-
fn remove_slashes(req: &mut iron::Request) -> iron::IronResult<iron::Response> {
210-
let mut url: iron::url::Url = req.url.clone().into();
211-
url.set_path(&url.path().trim_end_matches('/').to_string());
212-
Ok(iron::Response::with((
213-
iron::status::Found,
214-
iron::modifiers::Redirect(iron::Url::parse(&url.to_string()).unwrap()),
215-
)))
215+
#[derive(Copy, Clone)]
216+
struct SimpleRedirect {
217+
url_mangler: fn(&mut iron::url::Url),
218+
}
219+
220+
impl SimpleRedirect {
221+
fn new(url_mangler: fn(&mut iron::url::Url)) -> Self {
222+
Self { url_mangler }
223+
}
224+
}
225+
226+
impl Handler for SimpleRedirect {
227+
fn handle(&self, req: &mut iron::Request) -> iron::IronResult<iron::Response> {
228+
let mut url: iron::url::Url = req.url.clone().into();
229+
(self.url_mangler)(&mut url);
230+
Ok(iron::Response::with((
231+
iron::status::Found,
232+
iron::modifiers::Redirect(iron::Url::parse(&url.to_string()).unwrap()),
233+
)))
234+
}
216235
}
217236

218237
/// Iron Middleware that prevents requests to blacklisted prefixes.

0 commit comments

Comments
 (0)