hyperium / http

Rust HTTP types
Apache License 2.0
1.12k stars 283 forks source link

Add a `Display` impl for `Request` and `Response` to reconstruct the raw HTTP message #671

Closed tgross35 closed 5 months ago

tgross35 commented 5 months ago

This is just a convenient way to view the entire request or response as the server sees it, and allow easier copy & paste to other applications. I have a rough implementation that I use, which does not include extensions:

// This is a wrapper over Response<axum::body::Boxy>

impl fmt::Display for TestResponse {
    /// Print as a raw HTTP response
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "{:?} {}", self.parts.version, self.parts.status)?;
        for (name, value) in &self.parts.headers {
            writeln!(f, "{name}: {}", String::from_utf8_lossy(value.as_bytes()))?;
        }
        writeln!(f, "\n{}", String::from_utf8_lossy(&self.body))
    }
}

The result is alright:

HTTP/1.1 200 OK
content-type: application/json
content-length: 1016
access-control-allow-origin: *
vary: origin, access-control-request-method, access-control-request-headers

{"username": ...}

This could be a standalone trait or method as well, to better handle the generic body that might not want to implement Display.

seanmonstar commented 5 months ago

This has been discussed in a few issues, which are linked from #651.

tgross35 commented 5 months ago

Ah, thanks for the link. Do you know of any crates that handle serialization of these http types?