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

标签 asynchronous rust rust-actix actix-web

我想将 Actix-Web 请求主体转发到响应主体(类似于 echo),但它给出了一个不匹配的类型错误。

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]>`

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

最佳答案

你试图在没有 Boxing 的情况下返回一个 Future,你正在 Boxing Map 中的响应的关闭,而不是预期的 Future。使用 futures::future::ok 不是必需的,因为你的 request.body 已经是 future 的了。

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

关于asynchronous - 将请求正文转发到 Actix-Web 中的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54298923/

相关文章:

rust - 如何使用actix_web::guard::Header?

c# - 为什么应该在任务 C# 中使用结果?

rust - 在 T 和 UnsafeCell<T> 之间转换是否安全且已定义行为?

rust - 如何从Rust语言的函数返回闭包? [复制]

rust - Hyper 中的共享可变状态

rust - 如何对余额编号进行算术运算以避免在NEAR智能合约中溢出?

rust - 返回响应后,在后台运行长时间运行的异步函数

node.js - 为 Nodejs 递归扫描 AWS Dynamo DB 的函数

javascript - if语句中的异步调用最终执行else语句

c# - 在 ASP.NET 中异步发送电子邮件的正确方法...(我做对了吗?)