Error: The trait `Handler<_>` is not implemented for `fn() -> HttpResponse
Asked Answered
D

2

8

If I was to use this code on Actix Web 3 it would work, but I need to use the latest stable release... so 4^.

Here is the snippet in question (actually this is the entirety of my code):

use actix_web::{web, App, HttpResponse, HttpServer, ResponseError, Handler};


 fn hello_world() -> HttpResponse {
    HttpResponse::Ok().body("Hello, Mr. World") }
 
 #[actix_web::main] async fn main() -> std::io::Result<()> {
     HttpServer::new(move || App::new().route("hello", web::get().to(hello_world)))
         .bind("0.0.0.0:8000")?
         .run()
         .await
 }

Here is the error I get in version 4 or higher.

web::get().to(hello_world)))
    |                                                                  -- ^^^^^^^^^^^ the trait `Handler<_>` is not implemented for `fn() -> HttpResponse {hello_world}`
    |                                                                  |
    |                                                                  required by a bound introduced by this call
    |
note: required by a bound in `Route::to`
   --> /Users/xavierfontvillasenor/.cargo/registry/src/github.com-1ecc6299db9ec823/actix-web-4.1.0/src/route.rs:211:12
    |
211 |         F: Handler<Args>,
    |            ^^^^^^^^^^^^^ required by this bound in `Route::to`

When I add the trait,

impl Handler<T> for HttpResponse {
    type Output = ();
    type Future = ();

    fn call(&self, args: T) -> Self::Future {
        todo!()
    }
}

I get

impl Handler<T> for HttpResponse {
  |     -        ^ not found in this scope
  |     |
  |     help: you might be missing a type parameter: `<T>`

This works in V.3 why not now? What can I do?

Decapod answered 24/6, 2022 at 19:47 Comment(0)
M
8

You are not meant to implement Handler yourself, the issue is that handlers are required to be async functions, see the docs for more details:

// 👇
async fn hello_world() -> HttpResponse {
    HttpResponse::Ok().body("Hello, Mr. World")
}
Mathia answered 24/6, 2022 at 22:31 Comment(1)
Omg finally a response that makes sense! I am suffering with this for 3 days! These error messages were as bad as C++ templates in missdirection this time.Evapotranspiration
C
1

Actix Web v4 removed the implementation of Future for HttpResponse causing this error. The compiler is correct but it's not the most useful error. TL;DR: all handlers must be async.

See the migration guide

Crossstaff answered 26/6, 2022 at 4:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.