1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-01-18 22:01:50 +01:00
actix-web/guide/src/qs_12.md

44 lines
1.1 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 custom path pattern and `NamedFile`. To
2017-12-04 16:26:40 -08:00
match path tail we can use `[.*]` 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 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() {
2017-12-06 11:00:39 -08:00
Application::new("/")
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
2017-12-03 18:15:09 -08:00
.finish();
}
```
## Directory
2017-12-04 16:26:40 -08:00
To serve files from specific directory and sub-directories `StaticFiles` could be used.
2017-12-03 18:15:09 -08:00
`StaticFiles` could be registered with `Application::route` method.
```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() {
2017-12-06 11:00:39 -08:00
Application::new("/")
.resource("/static", |r| r.h(fs::StaticFiles::new(".", true)))
2017-12-03 18:15:09 -08:00
.finish();
}
```
2017-12-03 18:51:52 -08:00
First parameter is a base directory. Second parameter is *show_index*, if it is set to *true*
2017-12-03 18:15:09 -08: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.