use crate::{
middleware::{MiddleResult, Middleware},
response::ResponseBody,
HeaderType, Method, Request, Response,
};
pub struct Head {
streaming: bool,
}
impl Head {
pub fn new() -> Self {
Self { streaming: true }
}
pub fn streaming(mut self, streaming: bool) -> Self {
self.streaming = streaming;
self
}
}
impl Middleware for Head {
fn pre(&self, req: &mut Request) -> MiddleResult {
if req.method != Method::HEAD {
return MiddleResult::Continue;
}
req.method = Method::GET;
req.headers.add("afire::head", "true");
MiddleResult::Continue
}
fn post(&self, req: &Request, res: &mut Response) -> MiddleResult {
if !req.headers.has("afire::head") {
return MiddleResult::Continue;
}
let len = match &mut res.data {
_ if res.headers.has(HeaderType::ContentLength) => None,
ResponseBody::Static(d) => Some(d.len()),
ResponseBody::Stream(s) if self.streaming => {
let mut buf = Vec::new();
s.get_mut().read_to_end(&mut buf).unwrap();
Some(buf.len())
}
_ => None,
};
if let Some(i) = len {
res.headers.add(HeaderType::ContentLength, i.to_string());
}
res.data = ResponseBody::empty();
MiddleResult::Continue
}
}
impl Default for Head {
fn default() -> Self {
Self::new()
}
}