index : static-web-server.git

ascending towards madness

author Jose Quintana <joseluisquintana20@gmail.com> 2021-04-26 22:02:40.0 +00:00:00
committer Jose Quintana <joseluisquintana20@gmail.com> 2021-04-26 22:02:40.0 +00:00:00
commit
c0e49f441bdbf24d3f6be4c4b163f730b7b52e95 [patch]
tree
a5ed81782f96c7622874bd02e45bc0eb55403503
parent
2973035a85e1592292b18097b1b9c5f368af60b5
download
c0e49f441bdbf24d3f6be4c4b163f730b7b52e95.tar.gz

refactor: implement has_accept_encoding filter



Diff

 src/filters.rs   | 20 +++++++++++++++++---
 src/rejection.rs | 14 ++++++++++++++
 2 files changed, 31 insertions(+), 3 deletions(-)

diff --git a/src/filters.rs b/src/filters.rs
index b1766bf..bcc8b40 100644
--- a/src/filters.rs
+++ b/src/filters.rs
@@ -1,6 +1,20 @@
use warp::{reject, Filter, Rejection};

use crate::rejection::InvalidHeader;

/// Warp filter in order to check for an `Accept-Encoding` header value.
pub fn has_accept_encoding(
    val: &'static str,
) -> impl warp::Filter<Extract = (), Error = warp::Rejection> + Copy {
    warp::header::contains("accept-encoding", val)
    occurrence: &'static str,
) -> impl Filter<Extract = (), Error = Rejection> + Copy {
    warp::header::<String>("accept-encoding")
        .and_then(move |s: String| async move {
            if s.contains(occurrence) {
                Ok(())
            } else {
                Err(reject::custom(InvalidHeader {
                    name: "accept-encoding",
                }))
            }
        })
        .untuple_one()
}
diff --git a/src/rejection.rs b/src/rejection.rs
index 75a825a..8f99beb 100644
--- a/src/rejection.rs
+++ b/src/rejection.rs
@@ -44,3 +44,17 @@ pub async fn handle_rejection(err: Rejection) -> Result<impl Reply, Infallible> 

    Ok(warp::reply::with_status(warp::reply::html(content), code))
}

/// Custom invalid request header rejection.
#[derive(Debug)]
pub struct InvalidHeader {
    pub name: &'static str,
}

impl ::std::fmt::Display for InvalidHeader {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "Invalid request header {:?}", self.name)
    }
}

impl warp::reject::Reject for InvalidHeader {}