hyper-util icon indicating copy to clipboard operation
hyper-util copied to clipboard

Added Body wrapper

Open WinLinux1028 opened this issue 2 years ago • 4 comments

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())))
    }
}

WinLinux1028 avatar Dec 02 '23 08:12 WinLinux1028

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

davidpdrsn avatar Dec 02 '23 08:12 davidpdrsn

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

WinLinux1028 avatar Dec 02 '23 08:12 WinLinux1028

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.

davidpdrsn avatar Dec 02 '23 08:12 davidpdrsn

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);

WinLinux1028 avatar Dec 02 '23 08:12 WinLinux1028

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

seanmonstar avatar May 28 '24 12:05 seanmonstar