我正在尝试使用 serde_json 将请求正文解析为强类型对象:
#[macro_use]
extern crate serde_derive; // 1.0.70
extern crate futures; // 0.1.23
extern crate hyper; // 0.12.7
extern crate serde_json; // 1.0.24
use futures::{Future, Stream};
use hyper::{Body, Request};
struct AppError;
#[derive(Serialize, Deserialize)]
struct BasicLoginRequest {
email: String,
password: String,
}
impl BasicLoginRequest {
fn from(req: Request<Body>) -> Result<BasicLoginRequest, AppError> {
let body = req
.body()
.fold(Vec::new(), |mut v, chunk| {
v.extend(&chunk[..]);
futures::future::ok::<_, hyper::Error>(v)
}).and_then(move |chunks| {
let p: BasicLoginRequest = serde_json::from_slice(&chunks).unwrap();
futures::future::ok(p)
}).wait();
Ok(body.unwrap())
}
}
fn main() {}
我得到的错误是:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:20:20
|
20 | let body = req
| ____________________^
21 | | .body()
| |___________________^ cannot move out of borrowed content
来自 Cannot move out of borrowed content when unwrapping我知道展开时会发生此错误,因为需要一个值但提供了一个引用。
错误指向req.body()
;似乎 req.body()
返回一个引用,而不是一个值...
尝试处理正文的代码基于从 Extracting body from Hyper request as a string 中复制粘贴的摘录。
我如何使它工作?
最佳答案
我强烈建议阅读(至少略读)您使用的类型的文档,尤其是当您在使用它们时遇到问题时。
例如,Request::body
定义为:
pub fn body(&self) -> &T
接下来的两个方法是
-
pub fn body_mut(&mut self) -> &mut T
-
pub fn into_body(self) -> T
您想使用into_body
。
我还在我的网络浏览器中使用 Control-F 来搜索 -> T
一旦我知道非工作方法返回-> &T
.
关于rust - 无法移出尝试反序列化 hyper::Request.body() 的借用内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51819892/