我正在阅读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
会更好吗?
你必须将JsonValue
转换为字符串或字节,然后你可以将它设置为HttpResponse
体。您不能直接返回JsonValue
而不是box,因为请求正文读取过程是异步的。