【问题标题】:How do I access HttpRequest data inside a Future in Actix-web?如何在 Actix-web 的 Future 中访问 HttpRequest 数据?
【发布时间】:2018-07-08 10:08:57
【问题描述】:

我想要一个 Actix Web 处理程序,它通过将 POST 正文打印到控制台并构造一个包含来自请求对象的当前 URL 的 HTTP 响应来响应 POST 请求。

在读取请求的 POST 正文时,似乎需要涉及期货。到目前为止,我得到的最接近的是:

fn handler(req: HttpRequest) -> FutureResponse<HttpResponse> {
    req.body()
        .from_err()
        .and_then(|bytes: Bytes| {
            println!("Body: {:?}", bytes);
            let url = format!("{scheme}://{host}",
                scheme = req.connection_info().scheme(),
                host = req.connection_info().host());
            Ok(HttpResponse::Ok().body(url).into())
        }).responder()
}

这不会编译,因为 future 比处理程序更长寿,所以我尝试读取 req.connection_info() 是非法的。编译器错误建议我在闭包定义中使用move 关键字,即.and_then(move |bytes: Bytes| {。这也不会编译,因为reqreq.body() 调用上被移动,然后在移动后在构造url 的引用中被捕获。

在访问 POST 正文的同时,我可以访问附加到请求对象的数据(例如 connection_info),构建一个范围的合理方法是什么?

【问题讨论】:

标签: rust future lifetime rust-actix


【解决方案1】:

最简单的解决方案是在未来根本不访问它:

extern crate actix_web; // 0.6.14
extern crate bytes;     // 0.4.8
extern crate futures;   // 0.1.21

use actix_web::{AsyncResponder, FutureResponse, HttpMessage, HttpRequest, HttpResponse};
use bytes::Bytes;
use futures::future::Future;

fn handler(req: HttpRequest) -> FutureResponse<HttpResponse> {
    let url = format!(
        "{scheme}://{host}",
        scheme = req.connection_info().scheme(),
        host = req.connection_info().host(),
    );

    req.body()
        .from_err()
        .and_then(move |bytes: Bytes| {
            println!("Body: {:?}", bytes);
            Ok(HttpResponse::Ok().body(url).into())
        })
        .responder()
}

如果这不仅仅是出于演示目的的快速破解,那么通过连接字符串来构造 URL 是一个糟糕的主意,因为它不能正确地转义值。您应该使用为您执行此操作的类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 2018-07-27
    • 2011-06-17
    • 2021-01-06
    • 2019-04-27
    • 1970-01-01
    相关资源
    最近更新 更多