Return 来自 actix-web HttpRequest 的 JsonValue 对象
Return a JsonValue object from an actix-web HttpRequest
我正在阅读 actix-web 的示例,但由于我是 Rust 的新手,我在理解如何根据我的需要调整代码时遇到了一些问题。
给定一个 actix-web HttpRequest
,我想解析有效载荷和 return JsonValue
。我不知道如何将此功能更改为 return 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()
}
只 return JsonValue
而不是 Future
会更好吗?
您必须将JsonValue
转换为字符串或字节,然后才能将其设置为HttpResponse
正文。不能直接return一个JsonValue
代替box因为request body读取过程是异步的
我正在阅读 actix-web 的示例,但由于我是 Rust 的新手,我在理解如何根据我的需要调整代码时遇到了一些问题。
给定一个 actix-web HttpRequest
,我想解析有效载荷和 return JsonValue
。我不知道如何将此功能更改为 return 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()
}
只 return JsonValue
而不是 Future
会更好吗?
您必须将JsonValue
转换为字符串或字节,然后才能将其设置为HttpResponse
正文。不能直接return一个JsonValue
代替box因为request body读取过程是异步的