Skip to content

Commit 9358a7c

Browse files
committed
Update behavior of "I'm feeling lucky" button
Blaming a button isn't gonna change the fact that you are unlucky! Redirect to a random crate if "I'm feeling lucky"" button pressed without any search query. Fixes: #25
1 parent e330ef4 commit 9358a7c

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

src/web/releases.rs

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -361,9 +361,45 @@ pub fn search_handler(req: &mut Request) -> IronResult<Response> {
361361
// if there is a match
362362
// TODO: Redirecting to latest doc might be more useful
363363
if params.find(&["i-am-feeling-lucky"]).is_some() {
364+
365+
use iron::Url;
366+
use iron::modifiers::Redirect;
367+
368+
// redirect to a random crate if query is empty
369+
if query.is_empty() {
370+
let rows = conn.query("SELECT crates.name, \
371+
releases.version, \
372+
releases.target_name \
373+
FROM crates \
374+
INNER JOIN releases
375+
ON crates.latest_version_id = releases.id \
376+
WHERE github_stars >= 100 AND rustdoc_status = true \
377+
OFFSET FLOOR(RANDOM() * 280) LIMIT 1", &[]).unwrap();
378+
// ~~~~~~^
379+
// FIXME: This is a fast query but using a constant
380+
// There are currently 280 crates with docs and 100+
381+
// starts. This should be fine for a while.
382+
let name: String = rows.get(0).get(0);
383+
let version: String = rows.get(0).get(1);
384+
let target_name: String = rows.get(0).get(2);
385+
let url = Url::parse(&format!("{}://{}:{}/{}/{}/{}",
386+
req.url.scheme,
387+
req.url.host,
388+
req.url.port,
389+
name,
390+
version,
391+
target_name))
392+
.unwrap();
393+
394+
let mut resp = Response::with((status::Found, Redirect(url)));
395+
use iron::headers::{Expires, HttpDate};
396+
use time;
397+
resp.headers.set(Expires(HttpDate(time::now())));
398+
return Ok(resp);
399+
}
400+
401+
364402
if let Some(version) = match_version(&conn, &query, None) {
365-
use iron::Url;
366-
use iron::modifiers::Redirect;
367403
let url = Url::parse(&format!("{}://{}:{}/crate/{}/{}",
368404
req.url.scheme,
369405
req.url.host,

0 commit comments

Comments
 (0)