1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-24 07:53:00 +01:00

simplify StaticFiles

This commit is contained in:
Nikolay Kim 2018-04-06 19:34:55 -07:00
parent 602d78b76c
commit 542315ce7f
7 changed files with 35 additions and 29 deletions

View File

@ -129,7 +129,7 @@ fn main() {
io::Error::new(io::ErrorKind::Other, "test"), StatusCode::OK) io::Error::new(io::ErrorKind::Other, "test"), StatusCode::OK)
})) }))
// static files // static files
.handler("/static/", fs::StaticFiles::new("../static/", true)) .handler("/static/", fs::StaticFiles::new("../static/"))
// redirect // redirect
.resource("/", |r| r.method(Method::GET).f(|req| { .resource("/", |r| r.method(Method::GET).f(|req| {
println!("{:?}", req); println!("{:?}", req);

View File

@ -199,7 +199,7 @@ fn main() {
// websocket // websocket
.resource("/ws/", |r| r.route().f(chat_route)) .resource("/ws/", |r| r.route().f(chat_route))
// static resources // static resources
.handler("/static/", fs::StaticFiles::new("static/", true)) .handler("/static/", fs::StaticFiles::new("static/"))
}) })
.bind("127.0.0.1:8080").unwrap() .bind("127.0.0.1:8080").unwrap()
.start(); .start();

View File

@ -55,7 +55,7 @@ fn main() {
// websocket route // websocket route
.resource("/ws/", |r| r.method(http::Method::GET).f(ws_index)) .resource("/ws/", |r| r.method(http::Method::GET).f(ws_index))
// static files // static files
.handler("/", fs::StaticFiles::new("../static/", true) .handler("/", fs::StaticFiles::new("../static/")
.index_file("index.html"))) .index_file("index.html")))
// start http server on 127.0.0.1:8080 // start http server on 127.0.0.1:8080
.bind("127.0.0.1:8080").unwrap() .bind("127.0.0.1:8080").unwrap()

View File

@ -34,16 +34,21 @@ use actix_web::*;
fn main() { fn main() {
App::new() App::new()
.handler("/static", fs::StaticFiles::new(".", true)) .handler(
"/static",
fs::StaticFiles::new(".")
.show_folder_listing())
.finish(); .finish();
} }
``` ```
The first parameter is the base directory. If the second parameter, *show_index*, is set to **true**, The parameter is the base directory. By default files listing for sub-directories
the directory listing will be returned, and if it is set to **false**, is disabled. Attempt to load directory listing will return *404 Not Found* response.
*404 Not Found* will be returned. To enable files listing, use
[*StaticFiles::show_files_listing()*](../actix_web/s/struct.StaticFiles.html#method.show_files_listing)
method.
Instead of showing files listing for directory, it is possible to redirect to a specific Instead of showing files listing for directory, it is possible to redirect
index file. Use the to a specific index file. Use the
[*StaticFiles::index_file()*](../actix_web/s/struct.StaticFiles.html#method.index_file) [*StaticFiles::index_file()*](../actix_web/s/struct.StaticFiles.html#method.index_file)
method to configure this redirect. method to configure this redirect.

View File

@ -391,7 +391,7 @@ impl<S> App<S> where S: 'static {
/// let app = App::new() /// let app = App::new()
/// .middleware(middleware::Logger::default()) /// .middleware(middleware::Logger::default())
/// .configure(config) // <- register resources /// .configure(config) // <- register resources
/// .handler("/static", fs::StaticFiles::new(".", true)); /// .handler("/static", fs::StaticFiles::new("."));
/// } /// }
/// ``` /// ```
pub fn configure<F>(self, cfg: F) -> App<S> pub fn configure<F>(self, cfg: F) -> App<S>

View File

@ -538,8 +538,7 @@ impl ClientConnector {
self.install_wait_timeout(wait); self.install_wait_timeout(wait);
let waiter = Waiter{ tx, wait, conn_timeout }; let waiter = Waiter{ tx, wait, conn_timeout };
self.waiters.entry(key.clone()).or_insert_with(VecDeque::new) self.waiters.entry(key).or_insert_with(VecDeque::new).push_back(waiter);
.push_back(waiter);
rx rx
} }
} }
@ -553,12 +552,10 @@ impl Handler<Pause> for ClientConnector {
let mut timeout = Timeout::new(time, Arbiter::handle()).unwrap(); let mut timeout = Timeout::new(time, Arbiter::handle()).unwrap();
let _ = timeout.poll(); let _ = timeout.poll();
self.paused = Some(Some((when, timeout))); self.paused = Some(Some((when, timeout)));
} else { } else if self.paused.is_none() {
if self.paused.is_none() {
self.paused = Some(None); self.paused = Some(None);
} }
} }
}
} }
impl Handler<Resume> for ClientConnector { impl Handler<Resume> for ClientConnector {
@ -726,8 +723,7 @@ impl fut::ActorFuture for Maintenance
{ {
// check pause duration // check pause duration
let done = if let Some(Some(ref pause)) = act.paused { let done = if let Some(Some(ref pause)) = act.paused {
if pause.0 <= Instant::now() {true} else {false} pause.0 <= Instant::now() } else { false };
} else { false };
if done { if done {
act.paused.take(); act.paused.take();
} }

View File

@ -372,7 +372,7 @@ impl Responder for Directory {
/// ///
/// fn main() { /// fn main() {
/// let app = App::new() /// let app = App::new()
/// .handler("/static", fs::StaticFiles::new(".", true)) /// .handler("/static", fs::StaticFiles::new("."))
/// .finish(); /// .finish();
/// } /// }
/// ``` /// ```
@ -388,12 +388,9 @@ pub struct StaticFiles<S> {
} }
impl<S: 'static> StaticFiles<S> { impl<S: 'static> StaticFiles<S> {
/// Create new `StaticFiles` instance
/// /// Create new `StaticFiles` instance for specified base directory.
/// `dir` - base directory pub fn new<T: Into<PathBuf>>(dir: T) -> StaticFiles<S> {
///
/// `index` - show index for directory
pub fn new<T: Into<PathBuf>>(dir: T, index: bool) -> StaticFiles<S> {
let dir = dir.into(); let dir = dir.into();
let (dir, access) = match dir.canonicalize() { let (dir, access) = match dir.canonicalize() {
@ -415,7 +412,7 @@ impl<S: 'static> StaticFiles<S> {
directory: dir, directory: dir,
accessible: access, accessible: access,
index: None, index: None,
show_index: index, show_index: false,
cpu_pool: CpuPool::new(40), cpu_pool: CpuPool::new(40),
default: Box::new(WrapHandler::new( default: Box::new(WrapHandler::new(
|_| HttpResponse::new(StatusCode::NOT_FOUND))), |_| HttpResponse::new(StatusCode::NOT_FOUND))),
@ -424,6 +421,14 @@ impl<S: 'static> StaticFiles<S> {
} }
} }
/// Show files listing for directories.
///
/// By default show files listing is disabled.
pub fn show_files_listing(mut self) -> Self {
self.show_index = true;
self
}
/// Set index file /// Set index file
/// ///
/// Redirects to specific index file for directory "/" instead of /// Redirects to specific index file for directory "/" instead of
@ -523,7 +528,7 @@ mod tests {
#[test] #[test]
fn test_static_files() { fn test_static_files() {
let mut st = StaticFiles::new(".", true); let mut st = StaticFiles::new(".").show_files_listing();
st.accessible = false; st.accessible = false;
let resp = st.handle(HttpRequest::default()).respond_to(HttpRequest::default()).unwrap(); let resp = st.handle(HttpRequest::default()).respond_to(HttpRequest::default()).unwrap();
let resp = resp.as_response().expect("HTTP Response"); let resp = resp.as_response().expect("HTTP Response");
@ -548,7 +553,7 @@ mod tests {
#[test] #[test]
fn test_redirect_to_index() { fn test_redirect_to_index() {
let mut st = StaticFiles::new(".", false).index_file("index.html"); let mut st = StaticFiles::new(".").index_file("index.html");
let mut req = HttpRequest::default(); let mut req = HttpRequest::default();
req.match_info_mut().add("tail", "guide"); req.match_info_mut().add("tail", "guide");
@ -568,7 +573,7 @@ mod tests {
#[test] #[test]
fn test_redirect_to_index_nested() { fn test_redirect_to_index_nested() {
let mut st = StaticFiles::new(".", false).index_file("Cargo.toml"); let mut st = StaticFiles::new(".").index_file("Cargo.toml");
let mut req = HttpRequest::default(); let mut req = HttpRequest::default();
req.match_info_mut().add("tail", "examples/basics"); req.match_info_mut().add("tail", "examples/basics");