1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-25 00:12:59 +01:00
actix-extras/guide/src/qs_12.md

1.3 KiB

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.

# 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 could be registered with Application::resource method. StaticFiles requires tail named path expression for resource registration. And this name has to be used in StaticFile constructor.

# extern crate actix_web;
use actix_web::*;

fn main() {
    Application::new()
        .resource("/static/{tail:.*}", |r| r.h(fs::StaticFiles::new("tail", ".", true)))
        .finish();
}

First parameter is a name of path pattern. Second parameter is a base directory. Third 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.