1
0
mirror of https://github.com/actix/actix-extras.git synced 2025-01-24 15:51:47 +01:00

50 lines
1.4 KiB
Markdown
Raw Normal View History

2017-12-02 00:24:26 -08:00
# Static file handling
2017-12-03 18:15:09 -08:00
## Individual file
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()
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
2017-12-03 18:15:09 -08:00
.finish();
}
```
## Directory
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()
.handler("/static", fs::StaticFiles::new(".", true))
2017-12-03 18:15:09 -08:00
.finish();
}
```
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
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.