Unable to read and parse JSON body of Request using hyper (Solved)


#1

I used the following code to read and parse JSON body of the Request, however wait() blocks the running thread forever:

use hyper::server::{Request, Response};
use hyper::header::{ContentLength, ContentType};
use hyper::{Body, StatusCode, self};
use futures::stream::Stream;
use futures::Future;
use serde_json::{self, Value};

pub fn parse(req: Request) -> Response {
    let req_body = match req.body().concat2().wait() {
        Ok(body) => {
            if let Ok(value) = serde_json::from_slice(&body) {
                value
            } else {
                 return Response::new().with_status(StatusCode::InternalServerError);
            }
        },
        _ => return Response::new().with_status(StatusCode::InternalServerError),
    };

    // unreachable
    ...
}


#2

the code was changed to the following code and it is working now:

Box:new(req.body().concat2().and_then(|body| {
    let v: Value = serde_json::from_slice(&body).unwrap();
    // ...
}))

#3

I had a similar problem but .body() was giving me errors, (cannot move out of borrowed content) so I modified the solution here to be

let (parts, body) = request.into_parts();
return Box::new(body.concat2().and_then(move |bod| {

and that worked