use std::collections::HashMap;
use crate::Error;
pub struct Response {
protocol: String,
pub(crate) status: (u32, String),
pub(crate) headers: HashMap<String, Vec<String>>,
pub content: Vec<u8>
}
impl<A: Into<Response>, B: Into<Response>> Into<Response> for Result<A, B> {
fn into(self) -> Response {
match self {
Ok(v) => v.into(),
Err(e) => e.into()
}
}
}
impl<A: Into<String>> From<(u32, A)> for Response {
fn from(source: (u32, A)) -> Response {
Response {
protocol: "HTTP/1.1".into(),
status: (source.0, source.1.into()),
headers: HashMap::new(),
content: Vec::new()
}
}
}
impl Response {
const CONTINUE: (u32, &'static str) = (100, "Continue");
const SWITCHING_PROTOCOLS: (u32, &'static str) = (101, "Switching Protocols");
const OK: (u32, &'static str) = (200, "OK");
const CREATED: (u32, &'static str) = (201, "Created");
const ACCEPTED: (u32, &'static str) = (202, "Accepted");
const NON_AUTHORITATIVE_INFORMATION: (u32, &'static str) = (203, "Non-Authoritative Information");
const NO_CONTENT: (u32, &'static str) = (204, "No Content");
const RESET_CONTENT: (u32, &'static str) = (205, "Reset Content");
const PARTIAL_CONTENT: (u32, &'static str) = (206, "Partial Content");
const BAD_REQUEST: (u32, &'static str) = (400, "Bad Request");
const UNAUTHORIZED: (u32, &'static str) = (401, "Unauthorized");
const PAYMENT_REQUIRED: (u32, &'static str) = (402, "Payment Required");
const FORBIDDEN: (u32, &'static str) = (403, "Forbidden");
const NOT_FOUND: (u32, &'static str) = (404, "Not Found");
const INTERNAL_SERVER_ERROR: (u32, &'static str) = (500, "Internal Server Error");
const NOT_IMPLEMENTED: (u32, &'static str) = (501, "Not Implemented");
const BAD_GATEWAY: (u32, &'static str) = (502, "Bad Gateway");
const SERVICE_UNAVAILABLE: (u32, &'static str) = (503, "Service Unavailable");
pub fn r#continue() -> Response{ Response::CONTINUE.into() }
pub fn switching_protocols() -> Response{ Response::SWITCHING_PROTOCOLS.into() }
pub fn ok() -> Response { Response::OK.into() }
pub fn created() -> Response { Response::CREATED.into() }
pub fn accepted() -> Response { Response::ACCEPTED.into() }
pub fn non_authoritative_information() -> Response { Response::NON_AUTHORITATIVE_INFORMATION.into() }
pub fn no_content() -> Response { Response::NO_CONTENT.into() }
pub fn reset_content() -> Response { Response::RESET_CONTENT.into() }
pub fn partial_content() -> Response { Response::PARTIAL_CONTENT.into() }
pub fn bad_request() -> Response { Response::BAD_REQUEST.into() }
pub fn unauthorized() -> Response { Response::UNAUTHORIZED.into() }
pub fn payment_required() -> Response { Response::PAYMENT_REQUIRED.into() }
pub fn forbidden() -> Response { Response::FORBIDDEN.into() }
pub fn not_found() -> Response { Response::NOT_FOUND.into() }
pub fn internal_server_error() -> Response { Response::INTERNAL_SERVER_ERROR.into() }
pub fn not_implemented() -> Response { Response::NOT_IMPLEMENTED.into() }
pub fn bad_gateway() -> Response { Response::BAD_GATEWAY.into() }
pub fn service_unavailable() -> Response { Response::SERVICE_UNAVAILABLE.into() }
pub fn new() -> Response {
Response::OK.into()
}
pub fn header<A: Into<String>, B: Into<String>>(mut self, key: A, value: B) -> Response {
self.headers.entry(key.into()).or_insert_with(|| Vec::new()).push(value.into());
self
}
pub fn body<T: AsRef<[u8]>>(mut self, body: T) -> Response {
self.content = Vec::from(body.as_ref());
self
}
pub fn status_code(&self) -> u32 {
self.status.0
}
pub(crate) fn serialize(&mut self) -> Vec<u8> {
let mut response = format!("{} {} {}\r\n", self.protocol, self.status.0, self.status.1);
self.headers.entry("Content-Length".to_string()).or_insert_with(|| Vec::new()).push(format!("{}", self.content.len()));
for (header_name, headers) in &self.headers {
for header in headers {
response += &format!("{}: {}\r\n", header_name, header);
}
}
#[cfg(feature = "full_log")]
log::trace!("serializing http repsonse with headers: {}", response);
response += "\r\n";
let mut response = response.into_bytes();
response.extend_from_slice(&self.content);
response
}
pub(crate) fn parse<A: Into<Vec<u8>>>(bytes: A) -> Result<Response, Error> {
let mut source: Vec<u8> = bytes.into();
let (one, two) = (source.iter(), source.iter().skip(2));
let mut split_index = None;
for (idx, (a, b)) in one.zip(two).enumerate() {
if a==b && b==&b'\n' && idx > 0 && source[idx-1] == b'\r' && source[idx+1] == b'\r' {
split_index = Some(idx);
break;
}
}
let split_index = split_index.ok_or(Error::Parse(format!("no end of header was found")))?;
let mut content: Vec<_> = source.drain((split_index - 1)..).collect();
content.drain(..4);
let response_string = String::from_utf8(source).map_err(|e| Error::Parse(format!("{}", e)))?;
let mut lines = response_string.split("\r\n");
let first_line = lines.next().ok_or(Error::Parse("response has no first line".into()))?;
let tokens = first_line.split(" ").collect::<Vec<_>>();
let (protocol, code, status_text) = if tokens.len() < 3 {
return Err(Error::Parse("responses's first has incorrect format".into()));
} else {
(
tokens[0].to_string(),
tokens[1].parse::<u32>().map_err(|e| Error::custom(format!("{}", e)))?,
tokens[2..].join(" ")
)
};
let mut headers = HashMap::new();
for line in lines {
let idx = line.find(":").ok_or(Error::Parse(format!("corrupted header missing colon")))?;
let (key, value) = line.split_at(idx);
let (key, value) = (key.to_string(), value.trim_start_matches(": ").trim_end().to_string());
headers.entry(key).or_insert_with(|| Vec::new()).push(value);
}
Ok(Response {
protocol,
status: (code, status_text),
headers,
content
})
}
}