Skip to content

Commit

Permalink
#54 Add do_use_guard option
Browse files Browse the repository at this point in the history
  • Loading branch information
joepio committed Feb 4, 2023
1 parent 4187120 commit 69fdb81
Showing 1 changed file with 30 additions and 3 deletions.
33 changes: 30 additions & 3 deletions src/resource_files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use actix_web::{
header::{self, ContentType},
Method, StatusCode,
},
HttpMessage, HttpRequest, HttpResponse, ResponseError,
HttpMessage, HttpRequest, HttpResponse, ResponseError, guard::{Guard, GuardContext},
};
use derive_more::{Deref, Display, Error};
use futures_util::future::{ok, FutureExt, LocalBoxFuture, Ready};
Expand Down Expand Up @@ -38,8 +38,10 @@ use std::{collections::HashMap, ops::Deref, rc::Rc};
/// }
/// ```
#[allow(clippy::needless_doctest_main)]
#[derive(Clone)]
pub struct ResourceFiles {
not_resolve_defaults: bool,
use_guard: bool,
not_found_resolves_to: Option<String>,
inner: Rc<ResourceFilesInner>,
}
Expand All @@ -61,6 +63,7 @@ impl ResourceFiles {
inner: Rc::new(inner),
not_resolve_defaults: false,
not_found_resolves_to: None,
use_guard: false,
}
}

Expand All @@ -85,6 +88,14 @@ impl ResourceFiles {
pub fn resolve_not_found_to_root(self) -> Self {
self.resolve_not_found_to(INDEX_HTML)
}

/// Use guard to check if this request should be handled.
/// Can be useful if you want to serve static files from root, or another path that should also be used by other handlers.
/// By default guard is not used.
pub fn do_use_guard(mut self) -> Self {
self.use_guard = true;
self
}
}

impl Deref for ResourceFiles {
Expand All @@ -95,6 +106,17 @@ impl Deref for ResourceFiles {
}
}

impl Guard for ResourceFiles {
fn check(&self, ctx: &GuardContext<'_>) -> bool {
for filename in self.inner.files.keys() {
if *filename == ctx.head().uri.path() {
return true;
}
}
false
}
}

impl HttpServiceFactory for ResourceFiles {
fn register(self, config: &mut AppService) {
let prefix = self.path.trim_start_matches('/');
Expand All @@ -103,7 +125,12 @@ impl HttpServiceFactory for ResourceFiles {
} else {
ResourceDef::prefix(prefix)
};
config.register_service(rdef, None, self, None)
let guards: Option<Vec<Box<dyn Guard>>> = if self.use_guard {
Some(vec!(Box::new(self.clone())))
} else {
None
};
config.register_service(rdef, guards, self, None);
}
}

Expand Down Expand Up @@ -133,7 +160,7 @@ pub struct ResourceFilesService {
inner: Rc<ResourceFilesInner>,
}

impl<'a> Service<ServiceRequest> for ResourceFilesService {
impl Service<ServiceRequest> for ResourceFilesService {
type Response = ServiceResponse;
type Error = Error;
type Future = Ready<Result<Self::Response, Self::Error>>;
Expand Down

0 comments on commit 69fdb81

Please sign in to comment.