Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Body from Stream #1468

Closed
danneu opened this issue Mar 20, 2018 · 3 comments
Closed

Create Body from Stream #1468

danneu opened this issue Mar 20, 2018 · 3 comments

Comments

@danneu
Copy link

danneu commented Mar 20, 2018

Body implements Stream, but there doesn't seem to be a simple way to turn a chunk stream back into a Body.

For example, the most obvious gzip middleware would look like this:

fn gzip(body: Body) -> Body {
    let stream = body.and_then(|chunk| compress(chunk));
    Body::stream(Box::new(stream))
}

let response = Response::new();
let gzipped = Response::new().with_body(gzip(response.body()))

But as far as I can tell, the only tool Body gives us is Body::pair() so I suppose we do something like this:

fn gzip(pool: CpuPool, body: Body) -> Body {
    let stream = body.and_then(|chunk| compress(chunk));
    let (tx, body) = Body::pair();
    pool.spawn(tx.send_all(stream.map(Ok).map_err(|_| unreachable!())))
        .forget();
    body
}

It's not very user friendly. Nor am I sure if I implemented that correctly. It doesn't seem like the right abstraction for when you just want to transform the chunk stream.

For example, imagine if:

  • The body::Inner enum had a new variant Stream(Box<Stream<Chunk, Error>>)
  • Body's poll() impl had a new branch Stream(stream) => stream.poll()
  • Body had a new constructor Body::stream(stream)
@scottlamb
Copy link

I think you're in luck. (And me; I've been wanting this too.) Looks like 0.12.x is going to add it. See Body::wrap_stream on master and #1438.

@scottlamb
Copy link

btw, even now on 0.11.x, you don't have to use Body at all; you can instead use something like hyper::Response<Box<Stream<Item = Vec<u8>, Error = Error> + Send>>. The downside is that you may be giving up compatibility with libraries/frameworks that expect Body.

@danneu
Copy link
Author

danneu commented Mar 20, 2018

Sweet, thanks for illuminating. I look forward to trying 0.12.x.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants