use crate::http::ResponseReader;
pub struct RestResponse<'a> {
pub(crate) status: u16,
pub(crate) body_len: usize,
pub(crate) resp_reader: &'a ResponseReader,
pub(crate) chunked_body: Option<Vec<u8>>,
}
impl<'a> RestResponse<'a> {
pub fn new(status: u16, body_len: usize, resp_reader: &'a ResponseReader) -> Self {
Self {
status,
body_len,
resp_reader,
chunked_body: None,
}
}
pub fn new_chunked(status: u16, body: Vec<u8>, resp_reader: &'a ResponseReader) -> Self {
let body_len = body.len();
Self {
status,
body_len,
resp_reader,
chunked_body: Some(body),
}
}
pub fn status(&self) -> u16 {
self.status
}
pub fn header(&self, name: &str) -> Option<&str> {
self.resp_reader.header(name)
}
pub fn body(&self) -> &[u8] {
if let Some(ref chunked) = self.chunked_body {
return chunked;
}
let remainder = self.resp_reader.remainder();
&remainder[..self.body_len.min(remainder.len())]
}
pub fn body_str(&self) -> Result<&str, std::str::Utf8Error> {
std::str::from_utf8(self.body())
}
pub fn body_len(&self) -> usize {
self.body_len
}
#[cfg(feature = "bytes")]
pub fn body_to_bytes(&self) -> bytes::Bytes {
bytes::Bytes::copy_from_slice(self.body())
}
pub fn header_count(&self) -> usize {
self.resp_reader.header_count()
}
}
impl std::fmt::Debug for RestResponse<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RestResponse")
.field("status", &self.status)
.field("body_len", &self.body_len)
.finish()
}
}