将请求正文转发到 Actix-Web 中的响应

Forward request body to response in Actix-Web

我想将 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]>`

为什么会出现此错误,我该如何解决?

您正在尝试 return 一个 Future 而不 Boxing,您正在 Boxing Map 闭包中的响应,而不是预计 Future。使用 futures::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)
    }))
}