1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-24 16:02:59 +01:00
actix-extras/guide/src/qs_12.md
2018-03-31 00:16:55 -07:00

1.4 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 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 directory and sub-directories StaticFiles could be used. StaticFiles must be registered with App::handler() method otherwise it won't be able to serve sub-paths.

# extern crate actix_web;
use actix_web::*;

fn main() {
    App::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.

Instead of showing files listing for directory, it is possible to redirect to specific index file. Use StaticFiles::index_file() method to configure this redirect.