refactor: compress response only when Accept-Encoding is available
Diff
.gitignore | 2 ++
src/compression.rs | 17 +++++++++--------
src/handler.rs | 2 +-
src/server.rs | 2 +-
4 files changed, 13 insertions(+), 10 deletions(-)
@@ -15,6 +15,8 @@
**/*.env
**/*.svg
**/*.data
**/*.zst
**/*.out*
release
.vscode
TODO
@@ -51,16 +51,17 @@ pub fn auto(
return Ok(resp);
}
if let Some(content_type) = resp.headers().typed_get::<ContentType>() {
let content_type = content_type.to_string();
if !TEXT_MIME_TYPES.iter().any(|h| *h == content_type) {
return Ok(resp);
}
}
if let Some(ref accept_encoding) = headers.typed_get::<AcceptEncoding>() {
if let Some(encoding) = accept_encoding.prefered_encoding() {
if let Some(content_type) = resp.headers().typed_get::<ContentType>() {
let content_type = &content_type.to_string();
if !TEXT_MIME_TYPES.iter().any(|h| *h == content_type) {
return Ok(resp);
}
}
if encoding == ContentCoding::GZIP {
let (head, body) = resp.into_parts();
return Ok(gzip(head, body.into()));
@@ -5,7 +5,7 @@ use crate::{compression, static_files};
use crate::{error::Result, error_page};
pub async fn handle_request(base: &Path, req: Request<Body>) -> Result<Response<Body>> {
pub async fn handle_request(base: &Path, req: &Request<Body>) -> Result<Response<Body>> {
let headers = req.headers();
let method = req.method();
@@ -88,7 +88,7 @@ impl Server {
async move {
Ok::<_, error::Error>(service_fn(move |req| {
let root_dir = root_dir.clone();
async move { handler::handle_request(root_dir.as_ref(), req).await }
async move { handler::handle_request(root_dir.as_ref(), &req).await }
}))
}
});