mirror of
https://github.com/actix/actix-web.git
synced 2024-10-21 17:33:59 +00:00
1.4 KiB
1.4 KiB
Static file handling
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.
# extern crate actix_web;
use std::path::PathBuf;
use actix_web::{App, HttpRequest, Result, http::Method, fs::NamedFile};
fn index(req: HttpRequest) -> Result<NamedFile> {
let path: PathBuf = req.match_info().query("tail")?;
Ok(NamedFile::open(path)?)
}
fn main() {
App::new()
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
.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.
# extern crate actix_web;
use actix_web::*;
fn main() {
App::new()
.handler("/static", fs::StaticFiles::new(".", true))
.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.
Instead of showing files listing for directory, it is possible to redirect to a specific index file. Use the StaticFiles::index_file() method to configure this redirect.