Skip to content

Conversation

@WinLinux1028
Copy link

@WinLinux1028 WinLinux1028 commented Dec 2, 2023

This wrapper is useful when there is the possibility of returning various types of Body.
Like this:

async fn hello(req: Request<hyper::body::Incoming>) -> Result<Response<Body>, Infallible> {
    if req.uri().path() == "/" {
        Ok(Response::new(Body::new(Full::new(Bytes::from(
            "Hello, World!",
        )))))
    } else {
        Ok(Response::new(Body::new(Empty::<Bytes>::new())))
    }
}

@davidpdrsn
Copy link
Member

This already exists in http-body-util as BoxBody and UnsyncBoxBody.

@WinLinux1028
Copy link
Author

No, those aren't wrap Data and Error, but this wraps.

@davidpdrsn
Copy link
Member

You generally don’t need to wrap Data. It’ll be Bytes is most cases.

For error you can use .map_err to box it before wrapping it in BoxBody.

@WinLinux1028
Copy link
Author

WinLinux1028 commented Dec 2, 2023

That method can certainly be used, but it is a bit verbose (especially when wrapped in Request or Response).

let (parts, body) = response.into_parts();
let body = body.map_err(|e| Box::new(e));
let response = Response::from_parts(parts, BoxBody::new(body));
let response = Body::convert_response(response);

@seanmonstar
Copy link
Member

As mentioned, something very similar already exists in http-body-util.

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

Successfully merging this pull request may close these issues.

3 participants