Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use an async fn as a handler in Rocket?

I'm using Rocket framework and I want to make an async HTTP request in my handler, something like this

#[get("/")]
async fn handler() -> String {
  some_func().await;
  "OK".into()
}

And as a result, I get the next error

the trait `rocket::response::Responder<'_>` is not implemented for `impl core::future::future::Future`

I tried to write implementation but failed. Is there a way to implement trait for impl Trait?

Or maybe specify the return type of async fn so I can return my custom type with necessary traits implemented?

like image 909
KonstantinB Avatar asked Apr 20 '20 13:04

KonstantinB


People also ask

Does Rocket use tokio?

Rocket is a web framework that is built on top of Tokio. It uses async Rust and does a lot of our work for us. Rocket has some magical type macros that let us specify the inputs to our request handlers as normal Rust structs.

How does async work in Rust?

async transforms a block of code into a state machine that implements a trait called Future . Whereas calling a blocking function in a synchronous method would block the whole thread, blocked Future s will yield control of the thread, allowing other Future s to run. The value returned by async fn is a Future .


Video Answer


1 Answers

Until Rocket 0.5.0 is released you will have to use the development version for async routes. Notably this also means you can use stable Rust to compile.

In your Cargo.toml

rocket = { git = "https://github.com/SergioBenitez/Rocket" }
rocket_contrib = { git = "https://github.com/SergioBenitez/Rocket" }

Once using the development version you can write async routes exactly as you've done so in the question.

Note that various APIs may be different. See https://api.rocket.rs/master/rocket/index.html for documentation for the development version.

like image 193
jla Avatar answered Oct 09 '22 10:10

jla