rust 如何转换整个超响应,包括头部和所有部分,成字节?

yvfmudvl  于 2022-12-26  发布在  其他
关注(0)|答案(1)|浏览(108)

如何将hyper::Response对象转换为通过网络发送的字节,包括响应的所有部分(状态代码、版本、头和主体)?

oaxa6hgo

oaxa6hgo1#

以下是我目前得出的结论:

async fn response_to_bytes(response: Response<Full<Bytes>>) -> Vec<u8> {
        let (
            response::Parts {
                status,
                version,
                headers,
                extensions: _, // TODO: should we be using this?
                ..
            },
            body,
        ) = response.into_parts();

        // Enough for body + headers of length 64 each + 64 bytes for status line.
        // This will probably be more than enough most of the time.
        let mut bytes =
            BytesMut::with_capacity(body.size_hint().lower() as usize + 64 * headers.len() + 64);

        let version = match version {
            Version::HTTP_09 => "HTTP/0.9",
            Version::HTTP_10 => "HTTP/1.0",
            Version::HTTP_11 => "HTTP/1.1",
            Version::HTTP_2 => "HTTP/2",
            Version::HTTP_3 => "HTTP/3",
            _ => "HTTP/1.1", // TODO: handle this case.
        };

        // Status line.
        bytes.put(version.as_bytes()); // HTTP/1.1
        bytes.put(&b" "[..]);
        bytes.put(status.as_str().as_bytes()); // 200
        bytes.put(&b" "[..]);
        if let Some(reason) = status.canonical_reason() {
            bytes.put(reason.as_bytes()); // OK
        } else {
            bytes.put(&b"LOL"[..]); // TODO: ?
        }

        // Headers.
        for (name, value) in headers.into_iter() {
            if let Some(name) = name {
                bytes.put(&b"\r\n"[..]);
                bytes.put(name.as_str().as_bytes());
                bytes.put(&b": "[..]);
            } else {
                // TODO: are multiple values for the same header comma delimited?
                bytes.put(&b","[..])
            }
            bytes.put(value.as_bytes())
        }
        bytes.put(&b"\r\n\r\n"[..]);

        // Body.
        bytes.put(body.collect().await.unwrap().to_bytes()); // Unwrap Infallible.

        bytes.to_vec()
    }

相关问题