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

fix static files

This commit is contained in:
Nikolay Kim 2017-12-08 12:29:28 -08:00
parent 774bfc0a86
commit 3e91b06241
5 changed files with 35 additions and 16 deletions

View File

@ -5,14 +5,16 @@ Actix web is a small, fast, down-to-earth, open source rust web framework.
```rust,ignore ```rust,ignore
use actix_web::*; use actix_web::*;
fn index(req: HttpRequest) -> String { fn index(req: HttpRequest) -> String
format!("Hello {}!", &req.match_info()["name"]) {
format!("Hello {}!",
&req.match_info()["name"])
} }
fn main() { fn main() {
HttpServer::new( HttpServer::new(Application::new("/")
Application::new("/") .resource("/{name}",
.resource("/{name}", |r| r.method(Method::GET).f(index))) |r| r.method(Method::GET).f(index)))
.serve::<_, ()>("127.0.0.1:8080"); .serve::<_, ()>("127.0.0.1:8080");
} }
``` ```

View File

@ -80,7 +80,8 @@ fn main() {
} }
})) }))
// static files // static files
.resource("/static", |r| r.h(fs::StaticFiles::new("examples/static/", true))) .resource("/static/{tail:.*}",
|r| r.h(fs::StaticFiles::new("tail", "examples/static/", true)))
// redirect // redirect
.resource("/", |r| r.method(Method::GET).f(|req| { .resource("/", |r| r.method(Method::GET).f(|req| {
println!("{:?}", req); println!("{:?}", req);

View File

@ -67,7 +67,8 @@ fn main() {
// websocket route // websocket route
.resource("/ws/", |r| r.method(Method::GET).f(ws_index)) .resource("/ws/", |r| r.method(Method::GET).f(ws_index))
// static files // static files
.resource("/", |r| r.h(fs::StaticFiles::new("examples/static/", true)))) .resource("/{tail:.*}",
|r| r.h(fs::StaticFiles::new("tail", "examples/static/", true))))
// start http server on 127.0.0.1:8080 // start http server on 127.0.0.1:8080
.serve::<_, ()>("127.0.0.1:8080").unwrap(); .serve::<_, ()>("127.0.0.1:8080").unwrap();

View File

@ -25,7 +25,9 @@ fn main() {
## Directory ## Directory
To serve files from specific directory and sub-directories `StaticFiles` could be used. To serve files from specific directory and sub-directories `StaticFiles` could be used.
`StaticFiles` could be registered with `Application::route` method. `StaticFiles` could be registered with `Application::resource` method.
`StaticFiles` requires tail named path expression for resource registration.
And this name has to be used in `StaticFile` constructor.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
@ -33,11 +35,12 @@ use actix_web::*;
fn main() { fn main() {
Application::new("/") Application::new("/")
.resource("/static", |r| r.h(fs::StaticFiles::new(".", true))) .resource("/static/{tail:.*}", |r| r.h(fs::StaticFiles::new("tail", ".", true)))
.finish(); .finish();
} }
``` ```
First parameter is a base directory. Second parameter is *show_index*, if it is set to *true* First parameter is a name of path pattern. Second parameter is a base directory.
Third parameter is *show_index*, if it is set to *true*
directory listing would be returned for directories, if it is set to *false* directory listing would be returned for directories, if it is set to *false*
then *404 Not Found* would be returned instead of directory listing. then *404 Not Found* would be returned instead of directory listing.

View File

@ -191,7 +191,8 @@ impl FromRequest for FilesystemElement {
/// Static files handling /// Static files handling
/// ///
/// Can be registered with `Application::route_handler()`. /// Can be registered with `Application::resource()`. Resource path has to contain
/// tail named pattern and this name has to be used in `StaticFile` constructor.
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
@ -199,11 +200,12 @@ impl FromRequest for FilesystemElement {
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new("/") /// let app = Application::new("/")
/// .resource("/static", |r| r.h(fs::StaticFiles::new(".", true))) /// .resource("/static/{tail:.*}", |r| r.h(fs::StaticFiles::new("tail", ".", true)))
/// .finish(); /// .finish();
/// } /// }
/// ``` /// ```
pub struct StaticFiles { pub struct StaticFiles {
name: String,
directory: PathBuf, directory: PathBuf,
accessible: bool, accessible: bool,
show_index: bool, show_index: bool,
@ -217,7 +219,7 @@ impl StaticFiles {
/// `dir` - base directory /// `dir` - base directory
/// ///
/// `index` - show index for directory /// `index` - show index for directory
pub fn new<D: Into<PathBuf>>(dir: D, index: bool) -> StaticFiles { pub fn new<D: Into<PathBuf>>(name: &str, dir: D, index: bool) -> StaticFiles {
let dir = dir.into(); let dir = dir.into();
let (dir, access) = match dir.canonicalize() { let (dir, access) = match dir.canonicalize() {
@ -236,6 +238,7 @@ impl StaticFiles {
}; };
StaticFiles { StaticFiles {
name: name.to_owned(),
directory: dir, directory: dir,
accessible: access, accessible: access,
show_index: index, show_index: index,
@ -253,7 +256,13 @@ impl<S> Handler<S> for StaticFiles {
if !self.accessible { if !self.accessible {
Err(io::Error::new(io::ErrorKind::NotFound, "not found")) Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
} else { } else {
let relpath = PathBuf::from_param(&req.path()[req.prefix_len()..]) let path = if let Some(path) = req.match_info().get(&self.name) {
path
} else {
return Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
};
let relpath = PathBuf::from_param(path)
.map_err(|_| io::Error::new(io::ErrorKind::NotFound, "not found"))?; .map_err(|_| io::Error::new(io::ErrorKind::NotFound, "not found"))?;
// full filepath // full filepath
@ -291,7 +300,7 @@ mod tests {
#[test] #[test]
fn test_static_files() { fn test_static_files() {
let mut st = StaticFiles::new(".", true); let mut st = StaticFiles::new("tail", ".", true);
st.accessible = false; st.accessible = false;
assert!(st.handle(HttpRequest::default()).is_err()); assert!(st.handle(HttpRequest::default()).is_err());
@ -299,8 +308,11 @@ mod tests {
st.show_index = false; st.show_index = false;
assert!(st.handle(HttpRequest::default()).is_err()); assert!(st.handle(HttpRequest::default()).is_err());
let mut req = HttpRequest::default();
req.match_info_mut().add("tail", "");
st.show_index = true; st.show_index = true;
let resp = st.handle(HttpRequest::default()).from_request(HttpRequest::default()).unwrap(); let resp = st.handle(req).from_request(HttpRequest::default()).unwrap();
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/html; charset=utf-8"); assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/html; charset=utf-8");
assert!(resp.body().is_binary()); assert!(resp.body().is_binary());
assert!(format!("{:?}", resp.body()).contains("README.md")); assert!(format!("{:?}", resp.body()).contains("README.md"));