2017-12-02 09:24:26 +01:00
|
|
|
# Static file handling
|
2017-12-04 03:15:09 +01:00
|
|
|
|
|
|
|
## Individual file
|
|
|
|
|
2017-12-04 23:07:53 +01:00
|
|
|
It is possible to serve static files with custom path pattern and `NamedFile`. To
|
|
|
|
match path tail we can use `.*` regex.
|
2017-12-04 03:15:09 +01:00
|
|
|
|
|
|
|
```rust
|
|
|
|
extern crate actix_web;
|
|
|
|
use actix_web::*;
|
|
|
|
use std::path::PathBuf;
|
|
|
|
|
|
|
|
fn index(req: HttpRequest) -> Result<fs::NamedFile> {
|
|
|
|
let path: PathBuf = req.match_info().query("tail")?;
|
|
|
|
Ok(fs::NamedFile::open(path)?)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
Application::default("/")
|
2017-12-04 23:07:53 +01:00
|
|
|
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
|
2017-12-04 03:15:09 +01:00
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
## Directory
|
|
|
|
|
2017-12-04 03:51:52 +01:00
|
|
|
To serve files from specific directory and sub-directories `StaticFiles` type could be used.
|
2017-12-04 03:15:09 +01:00
|
|
|
`StaticFiles` could be registered with `Application::route` method.
|
|
|
|
|
|
|
|
```rust
|
|
|
|
extern crate actix_web;
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
actix_web::Application::default("/")
|
2017-12-04 23:53:40 +01:00
|
|
|
.route("/static", |r| r.h(actix_web::fs::StaticFiles::new(".", true)))
|
2017-12-04 03:15:09 +01:00
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2017-12-04 03:51:52 +01:00
|
|
|
First parameter is a base directory. Second parameter is *show_index*, if it is set to *true*
|
2017-12-04 03:15:09 +01:00
|
|
|
directory listing would be returned for directories, if it is set to *false*
|
|
|
|
then *404 Not Found* would be returned instead of directory listing.
|