Search code examples
rusthyper

Return a struct from a body stream


Please assist, i have looked at the hyper doc and example

Most examples when dealing with hyper Request<Body> will either map(|chunk|{ //do something }) or and_then(|chunk|{ //do something }) then return the Stream, that works but now i want to try and return the chunk or actual item in the stream. see below

pub fn to_struct(body: Body) -> Option<Person> {
    let person = body.and_then(|chunk|{
        let body = std::str::from_utf8(&chunk).unwrap();
        let results: Person = serde_json::from_str(&body).unwrap();
        Ok(results)
    });
    // match person or if let 
    // return Some or None

    // Don't wan't to Body::wrap_stream(person) then return Response<Body>
}

streams do nothing unless polled now i want to poll the following stream and return the results.await might solve the issue i believe but i am using rust Stable. I wish to poll() but i will receive a NotReady.Please advise.


Solution

  • You are trying to use hyper synchronously, by nature hyper is not made for that and require a layer of abstraction, you should look at this issus

    There is no documentation specifically to that effect. Since
    you'd need to block the thread at a certain point in execution
    until it is ready, you'd need the work of the event loop to occur
    in another thread, and send the results over a channel that you
    block on.
    
    Alternatively, you can look at reqwest, which even with the hyper
    upgrade (not quite released to crate.io, but super soon), it
    still offers a synchronous API besides the new async API.
    

    Note: reqwest is now released on crate.io