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
|
2017-12-05 01:26:40 +01:00
|
|
|
match path tail we can use `[.*]` regex.
|
2017-12-04 03:15:09 +01:00
|
|
|
|
|
|
|
```rust
|
2017-12-05 01:26:40 +01:00
|
|
|
# extern crate actix_web;
|
2017-12-04 03:15:09 +01:00
|
|
|
use std::path::PathBuf;
|
2018-03-31 09:16:55 +02:00
|
|
|
use actix_web::{App, HttpRequest, Result, http::Method, fs::NamedFile};
|
2017-12-04 03:15:09 +01:00
|
|
|
|
2018-03-31 02:31:18 +02:00
|
|
|
fn index(req: HttpRequest) -> Result<NamedFile> {
|
2017-12-04 03:15:09 +01:00
|
|
|
let path: PathBuf = req.match_info().query("tail")?;
|
2018-03-31 02:31:18 +02:00
|
|
|
Ok(NamedFile::open(path)?)
|
2017-12-04 03:15:09 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2018-03-31 09:16:55 +02:00
|
|
|
App::new()
|
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
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
To serve files from specific directory and sub-directories `StaticFiles` could be used.
|
2018-03-31 09:16:55 +02:00
|
|
|
`StaticFiles` must be registered with `App::handler()` method otherwise
|
2018-03-28 22:16:01 +02:00
|
|
|
it won't be able to serve sub-paths.
|
2017-12-04 03:15:09 +01:00
|
|
|
|
|
|
|
```rust
|
2017-12-05 01:26:40 +01:00
|
|
|
# extern crate actix_web;
|
|
|
|
use actix_web::*;
|
2017-12-04 03:15:09 +01:00
|
|
|
|
|
|
|
fn main() {
|
2018-03-31 09:16:55 +02:00
|
|
|
App::new()
|
2018-01-03 00:23:31 +01:00
|
|
|
.handler("/static", fs::StaticFiles::new(".", true))
|
2017-12-04 03:15:09 +01:00
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2018-01-03 00:23:31 +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.
|
2018-01-29 12:23:45 +01:00
|
|
|
|
|
|
|
Instead of showing files listing for directory, it is possible to redirect to specific
|
2018-03-28 22:16:01 +02:00
|
|
|
index file. Use
|
2018-01-29 12:23:45 +01:00
|
|
|
[*StaticFiles::index_file()*](../actix_web/s/struct.StaticFiles.html#method.index_file)
|
|
|
|
method to configure this redirect.
|