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()
}
1条答案
按热度按时间oaxa6hgo1#
以下是我目前得出的结论: