【问题标题】:Return a JsonValue object from an actix-web HttpRequest从 actix-web HttpRequest 返回一个 JsonValue 对象
【发布时间】:2018-09-16 02:38:43
【问题描述】:

我正在阅读 actix-web 的示例,但由于我对 Rust 还很陌生,所以在理解如何使代码适应我的需求时遇到了一些问题。

给定一个 actix-web HttpRequest,我想解析有效负载并返回一个 JsonValue。我不知道如何更改此函数以返回 JsonValue 而不是 HttpResponse

fn index_mjsonrust(req: &HttpRequest, ) -> Box<Future<Item = HttpResponse, Error = Error>> {
    req.payload()
        .concat2()
        .from_err()
        .and_then(|body| {
            // body is loaded, now we can deserialize json-rust
            let result = json::parse(std::str::from_utf8(&body).unwrap()); // return Result
            let injson: JsonValue = match result {
                Ok(v) => v,
                Err(e) => object!{"err" => e.to_string() },
            };
            Ok(HttpResponse::Ok()
                .content_type("application/json")
                .body(injson.dump()))
        })
        .responder()
}

只返回 JsonValue 而不是 Future 会更好吗?

【问题讨论】:

  • 请查看如何创建minimal reproducible example,然后查看edit 您的问题以包含它。我们无法分辨代码中存在哪些 crate(和版本)、类型、特征、字段等。显示所有导入的类型很重要。寻求调试帮助的问题必须包括特定错误重现该错误所需的最短代码。尝试在Rust Playground 上重现您的错误,或者您可以在全新的 Cargo 项目中重现它。还有Rust-specific MCVE tips

标签: rust rust-actix


【解决方案1】:

您必须将JsonValue 转换为字符串或字节,然后您可以将其设置为HttpResponse 正文。不能直接返回JsonValue而不是box,因为请求体读取过程是异步的。

【讨论】:

    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 2015-02-18
    相关资源
    最近更新 更多