2017-12-02 00:24:26 -08:00
|
|
|
# Static file handling
|
2017-12-03 18:15:09 -08:00
|
|
|
|
|
|
|
## Individual file
|
|
|
|
|
2018-04-06 18:40:57 -04:00
|
|
|
It is possible to serve static files with a custom path pattern and `NamedFile`. To
|
|
|
|
match a path tail, we can use a `[.*]` regex.
|
2017-12-03 18:15:09 -08:00
|
|
|
|
|
|
|
```rust
|
2017-12-04 16:26:40 -08:00
|
|
|
# extern crate actix_web;
|
2017-12-03 18:15:09 -08:00
|
|
|
use std::path::PathBuf;
|
2018-03-31 00:16:55 -07:00
|
|
|
use actix_web::{App, HttpRequest, Result, http::Method, fs::NamedFile};
|
2017-12-03 18:15:09 -08:00
|
|
|
|
2018-03-30 17:31:18 -07:00
|
|
|
fn index(req: HttpRequest) -> Result<NamedFile> {
|
2017-12-03 18:15:09 -08:00
|
|
|
let path: PathBuf = req.match_info().query("tail")?;
|
2018-03-30 17:31:18 -07:00
|
|
|
Ok(NamedFile::open(path)?)
|
2017-12-03 18:15:09 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2018-03-31 00:16:55 -07:00
|
|
|
App::new()
|
2017-12-04 14:07:53 -08:00
|
|
|
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
|
2017-12-03 18:15:09 -08:00
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
## Directory
|
|
|
|
|
2018-04-06 18:40:57 -04:00
|
|
|
To serve files from specific directories and sub-directories, `StaticFiles` can be used.
|
|
|
|
`StaticFiles` must be registered with an `App::handler()` method, otherwise
|
|
|
|
it will be unable to serve sub-paths.
|
2017-12-03 18:15:09 -08:00
|
|
|
|
|
|
|
```rust
|
2017-12-04 16:26:40 -08:00
|
|
|
# extern crate actix_web;
|
|
|
|
use actix_web::*;
|
2017-12-03 18:15:09 -08:00
|
|
|
|
|
|
|
fn main() {
|
2018-03-31 00:16:55 -07:00
|
|
|
App::new()
|
2018-01-02 15:23:31 -08:00
|
|
|
.handler("/static", fs::StaticFiles::new(".", true))
|
2017-12-03 18:15:09 -08:00
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2018-04-06 18:40:57 -04:00
|
|
|
The first parameter is the base directory. If the second parameter, *show_index*, is set to **true**,
|
|
|
|
the directory listing will be returned, and if it is set to **false**,
|
|
|
|
*404 Not Found* will be returned.
|
2018-01-29 03:23:45 -08:00
|
|
|
|
2018-04-06 18:40:57 -04:00
|
|
|
Instead of showing files listing for directory, it is possible to redirect to a specific
|
|
|
|
index file. Use the
|
2018-01-29 03:23:45 -08:00
|
|
|
[*StaticFiles::index_file()*](../actix_web/s/struct.StaticFiles.html#method.index_file)
|
|
|
|
method to configure this redirect.
|