2017-12-02 08:24:26 +00:00
|
|
|
# Static file handling
|
2017-12-04 02:15:09 +00:00
|
|
|
|
|
|
|
## Individual file
|
|
|
|
|
2018-04-06 22:40:57 +00: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-04 02:15:09 +00:00
|
|
|
|
|
|
|
```rust
|
2017-12-05 00:26:40 +00:00
|
|
|
# extern crate actix_web;
|
2017-12-04 02:15:09 +00:00
|
|
|
use std::path::PathBuf;
|
2018-03-31 07:16:55 +00:00
|
|
|
use actix_web::{App, HttpRequest, Result, http::Method, fs::NamedFile};
|
2017-12-04 02:15:09 +00:00
|
|
|
|
2018-03-31 00:31:18 +00:00
|
|
|
fn index(req: HttpRequest) -> Result<NamedFile> {
|
2017-12-04 02:15:09 +00:00
|
|
|
let path: PathBuf = req.match_info().query("tail")?;
|
2018-03-31 00:31:18 +00:00
|
|
|
Ok(NamedFile::open(path)?)
|
2017-12-04 02:15:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2018-03-31 07:16:55 +00:00
|
|
|
App::new()
|
2017-12-04 22:07:53 +00:00
|
|
|
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
|
2017-12-04 02:15:09 +00:00
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
## Directory
|
|
|
|
|
2018-04-06 22:40:57 +00: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-04 02:15:09 +00:00
|
|
|
|
|
|
|
```rust
|
2017-12-05 00:26:40 +00:00
|
|
|
# extern crate actix_web;
|
|
|
|
use actix_web::*;
|
2017-12-04 02:15:09 +00:00
|
|
|
|
|
|
|
fn main() {
|
2018-03-31 07:16:55 +00:00
|
|
|
App::new()
|
2018-04-07 02:34:55 +00:00
|
|
|
.handler(
|
|
|
|
"/static",
|
|
|
|
fs::StaticFiles::new(".")
|
2018-04-07 03:24:49 +00:00
|
|
|
.show_files_listing())
|
2017-12-04 02:15:09 +00:00
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2018-04-07 02:34:55 +00:00
|
|
|
The parameter is the base directory. By default files listing for sub-directories
|
|
|
|
is disabled. Attempt to load directory listing will return *404 Not Found* response.
|
|
|
|
To enable files listing, use
|
|
|
|
[*StaticFiles::show_files_listing()*](../actix_web/s/struct.StaticFiles.html#method.show_files_listing)
|
|
|
|
method.
|
2018-01-29 11:23:45 +00:00
|
|
|
|
2018-04-07 02:34:55 +00:00
|
|
|
Instead of showing files listing for directory, it is possible to redirect
|
|
|
|
to a specific index file. Use the
|
2018-01-29 11:23:45 +00:00
|
|
|
[*StaticFiles::index_file()*](../actix_web/s/struct.StaticFiles.html#method.index_file)
|
|
|
|
method to configure this redirect.
|