从actix-web HttpRequest返回一个JsonValue对象

问题描述 投票:0回答:1

我正在阅读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会更好吗?

rust rust-actix
1个回答
2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.