http-body icon indicating copy to clipboard operation
http-body copied to clipboard

feat(util): add ResponseExt trait

Open joshka opened this issue 1 year ago • 2 comments

This adds a ResponseExt trait to the http_body_util crate. This trait provides two methods, box_body and box_body_unsync, which allow you to box the body of an http::Response to make writing code that returns responses with different body types easier.

use bytes::Bytes;
use http::{Response, StatusCode};
use http_body_util::{Empty, Full, ResponseExt};

let response = match uri.path() {
    "/greeting" => greeting().box_body(),
    "/empty" => empty().box_body(),
    _ => not_found().box_body(),
}

fn greeting() -> Response<String> {
    Response::new("Hello, World!".to_string())
}

fn empty() -> Response<Empty<Bytes>> {
    Response::new(Empty::new())
}

fn not_found() -> Response<Full<Bytes>> {
    Response::builder()
        .status(StatusCode::NOT_FOUND)
        .body("Not Found".into())
        .unwrap()
}

joshka avatar Mar 25 '25 03:03 joshka