mirror of
https://github.com/fafhrd91/actix-web
synced 2024-12-01 02:54:36 +01:00
45 lines
1.1 KiB
Markdown
45 lines
1.1 KiB
Markdown
# Static file handling
|
|
|
|
## Individual file
|
|
|
|
It is possible to serve static files with custom path pattern and `NamedFile`. To
|
|
match path tail we can use `[.*]` regex.
|
|
|
|
```rust
|
|
# extern crate actix_web;
|
|
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() {
|
|
Application::new()
|
|
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
|
|
.finish();
|
|
}
|
|
```
|
|
|
|
## Directory
|
|
|
|
To serve files from specific directory and sub-directories `StaticFiles` could be used.
|
|
`StaticFiles` must be registered with `Application::handler()` method otherwise
|
|
it won't be able to server sub-paths.
|
|
|
|
```rust
|
|
# extern crate actix_web;
|
|
use actix_web::*;
|
|
|
|
fn main() {
|
|
Application::new()
|
|
.handler("/static", fs::StaticFiles::new(".", true))
|
|
.finish();
|
|
}
|
|
```
|
|
|
|
First parameter is a base directory. Second parameter is *show_index*, if it is set to *true*
|
|
directory listing would be returned for directories, if it is set to *false*
|
|
then *404 Not Found* would be returned instead of directory listing.
|