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

3
我希望将Actix-Web请求体转发到响应体中(类似于回声),但出现了“类型不匹配”错误。
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]>`

为什么会出现这个错误,我该如何修复它?
1个回答

3

您正在尝试返回一个未经Box处理的Future,在Map的闭包中Box化响应,而不是预期的Future。因为您的request.body已经是future,使用futures::future::ok是不必要的。

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)
    }))
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接