3

我想将 Actix-Web 请求正文转发到响应正文(类似于 echo),但它给出了mismatched types错误。

use actix_web::*;
use futures::future::ok;
use futures::Future;

fn show_request(
    request: &actix_web::HttpRequest
) -> Box<Future<Item=HttpResponse, Error=Error>> {
    request
        .body()
        .from_err::<actix_web::error::PayloadError>()
        .map(move |f| {
            Box::new(ok(actix_web::HttpResponse::Ok()
                .content_type("text/plain")
                .body(f)))
        })
}

pub fn index(scope: actix_web::Scope<()>) -> actix_web::Scope<()> {
    scope.handler("", |req: &actix_web::HttpRequest| {
        show_request(req)
    })
}

fn main() {
    actix_web::server::new(|| {
        vec![
            actix_web::App::new()
                .scope("", index)
                .boxed(),

        ]
    }).bind("127.0.0.1:8000")
        .expect("Can not bind to port 8000")
        .run();
}

[package]
name = "temp"
version = "0.1.0"
authors = ["John"]
edition = "2018"

[dependencies]
actix-web = "0.7"
futures = "0.1"

错误:

error[E0308]: mismatched types
  --> src/proj.rs:50:2
   |
49 |   ) -> Box<Future<Item=HttpResponse, Error=Error>> {
   |        ------------------------------------------- expected `std::boxed::Box<(dyn futures::Future<Error=actix_web::Error, Item=actix_web::HttpResponse> + 'static)>` because of return type
50 |       request
   |  _____^
51 | |         .body()
52 | |         .from_err::<actix_web::error::PayloadError>()
53 | |         .map(move |f| {
...  |
56 | |                 .body(f)))
57 | |         })
   | |__________^ expected struct `std::boxed::Box`, found struct `futures::Map`
   |
   = note: expected type `std::boxed::Box<(dyn futures::Future<Error=actix_web::Error, Item=actix_web::HttpResponse> + 'static)>`
              found type `futures::Map<futures::future::FromErr<actix_web::dev::MessageBody<actix_web::HttpRequest>, actix_web::error::PayloadError>, [closure@src/.rs:53:8: 57:4]>`

为什么会发生此错误,我该如何解决?

4

1 回答 1

3

您正在尝试返回 a Futurewithout Boxing,您正在Boxing 关闭响应Map,而不是预期的Futurefutures::future::ok没有必要使用,因为您request.body已经是未来。

fn show_request(
    request: &actix_web::HttpRequest,
) -> Box<Future<Item = HttpResponse, Error = Error>> {
    Box::new(request.body().map_err(|e| e.into()).map(move |f| {
        actix_web::HttpResponse::Ok()
            .content_type("text/plain")
            .body(f)
    }))
}
于 2019-01-22T07:34:43.177 回答