user18511546
user18511546

Reputation:

How to catch all routes in rocket?

I have looked up everywhere but I only found this github issue, but it's from 5 years ago, and rocket has changed a lot. Is there a way to catch all methods (get, post, head, options, whatever .. .) and all routes (/abc, /abc/xyz, /xyz, /whatever) in rocket.

I tried using the code from the github issue, but rocket api has updated a lot so I can't figure out how.

Upvotes: 1

Views: 2102

Answers (1)

Jakub Dąbek
Jakub Dąbek

Reputation: 1044

What you want to do is part of "manual routing" in Rocket, the code linked in the issue you found is now a dead link, but there's a similar example in the current version.
It uses the Handler trait with its impl for functions:

fn hi<'r>(req: &'r Request, _: Data<'r>) -> route::BoxFuture<'r> {
    route::Outcome::from(req, "Hello!").pin()
}

#[rocket::launch]
fn rocket() -> _ {
    let hello = Route::ranked(2, Get, "/", hi);

    rocket::build()
        .mount("/", vec![hello])
}

If you need multiple methods you can loop through them in the same way that's described in the issue and create the routes with

#[rocket::launch]
fn rocket() -> _ {
    use rocket::http::Method::*;
    let mut routes = vec![];
    for method in &[Get, Put, Post, Delete, Options, Head, Trace, Connect, Patch] {
        routes.push(Route::new(*method, "/git/<path..>", git_http));
    }
    rocket::build().mount("/", routes)
}

The <path..> captures all segments (query parameters are caught by default from my testing), and you can get to them using Request's methods.

Upvotes: 0

Related Questions