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



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

给定一个actix-webHttpRequest,我想解析有效载荷并返回一个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更好吗?

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

最新更新