use super::header::HTTPResponseHeaders;
use super::Body;
use super::StatusCode;
#[derive(Debug, PartialEq, Clone)]
pub struct HTTPResponse {
status: StatusCode,
header: Vec<HTTPResponseHeaders>,
body: Body,
}
impl HTTPResponse {
pub fn new(status: StatusCode, header: Vec<HTTPResponseHeaders>, body: Body) -> HTTPResponse {
HTTPResponse {
status,
header,
body,
}
}
pub fn try_to_string(&self) -> Result<String, std::string::FromUtf8Error> {
let mut header = String::new();
for i in &self.header {
header.push_str(format!("{}\r\n", i.to_string()).as_str());
}
match self.body.try_to_string() {
Ok(n) => Ok(format!(
"{}\r\n{}\r\n{}",
self.status.to_string(),
header,
n
)),
Err(e) => Err(e),
}
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut bytes: Vec<u8> = Vec::new();
for i in self.status.to_string().bytes() {
bytes.push(i);
}
bytes.push(0xD); bytes.push(0xA); for i in &self.header {
for j in i.to_string().bytes() {
bytes.push(j);
}
bytes.push(0xD); bytes.push(0xA); }
bytes.push(0xD); bytes.push(0xA); for i in self.body.get_bytes() {
bytes.push(*i);
}
bytes
}
pub fn get_status_code(&self) -> StatusCode {
self.status
}
pub fn get_headers(&self) -> &Vec<HTTPResponseHeaders> {
&self.header
}
pub fn get_body(&self) -> &Body {
&self.body
}
}