use super::*;
impl Default for CompressConfig {
fn default() -> Self {
Self::new(DEFAULT_MIN_LENGTH)
}
}
impl CompressConfig {
pub fn new(min_length: usize) -> Self {
Self { min_length }
}
pub fn get_min_length(&self) -> usize {
self.min_length
}
}
impl CompressMiddleware {
pub fn init(config: CompressConfig) -> Result<(), String> {
CONFIG
.set(config)
.map_err(|_: CompressConfig| "the compress configuration was already set".to_owned())
}
fn config() -> CompressConfig {
CONFIG.get().copied().unwrap_or_default()
}
fn negotiated_coding(request: &Request) -> Option<Compress> {
let values: &RequestHeadersValue = request.get_headers().get(ACCEPT_ENCODING)?;
let first: &String = values.front()?;
if values.len() == 1 {
return Compress::from_accept_encoding(first);
}
let joined: String = values.iter().cloned().collect::<Vec<String>>().join(COMMA);
Compress::from_accept_encoding(joined)
}
}
impl ServerHook for CompressMiddleware {
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
let Some(coding) = Self::negotiated_coding(ctx.get_request()) else {
return Status::Continue;
};
let response: &mut Response = ctx.get_mut_response();
if response.get_headers().contains_key(CONTENT_ENCODING)
|| response.get_body().len() < Self::config().get_min_length()
|| has_no_body(response.get_status_code())
|| is_event_stream(response)
{
return Status::Continue;
}
response.set_header(CONTENT_ENCODING, coding.as_str());
vary_accept_encoding(response);
Status::Continue
}
}
impl EntityTag {
pub fn strong(data: &[u8]) -> Self {
let mut hasher: XxHash3_64 = XxHash3_64::default();
hasher.write(data);
Self(format!(
"{ENTITY_TAG_QUOTE}{:016x}{ENTITY_TAG_QUOTE}",
hasher.finish()
))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl ConditionalMiddleware {
fn entity_tag(response: &mut Response) -> EntityTag {
let existing: Option<String> = response
.get_headers()
.get(ETAG)
.and_then(|values: &ResponseHeadersValue| values.back().cloned());
match existing {
Some(etag) => EntityTag(etag),
None => {
let etag: EntityTag = EntityTag::strong(response.get_body());
response.set_header(ETAG, etag.as_str());
etag
}
}
}
}
impl ServerHook for ConditionalMiddleware {
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
let method: &RequestMethod = ctx.get_request().get_method();
if !method.is_get() && !method.is_head() {
return Status::Continue;
}
if has_no_body(ctx.get_response().get_status_code()) {
return Status::Continue;
}
let etag: EntityTag = Self::entity_tag(ctx.get_mut_response());
if ctx.get_request().matches_if_none_match(etag.as_str()) {
ctx.get_mut_response()
.set_status_code(HttpStatus::NotModified.code())
.set_body(EMPTY_STR);
}
Status::Continue
}
}