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

时间:2019-01-21 22:59:49

标签: asynchronous rust rust-actix

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

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

1 个答案:

答案 0 :(得分:2)

您尝试返回Future,但不进行Box,而是BoxMap结束时而不是预期的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)
    }))
}