5

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?

Xavi Font
  • 296
  • 4
  • 19

2 Answers2

6

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")
}
Ibraheem Ahmed
  • 11,652
  • 2
  • 48
  • 54
  • 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. –  Jan 26 '23 at 15:13
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

robjtede
  • 736
  • 5
  • 16