Add support for static files

This commit is contained in:
2019-09-03 17:16:51 +02:00
parent 8bf9edee25
commit 9f259b1044
2 changed files with 15 additions and 0 deletions

View File

@@ -3,6 +3,7 @@ use super::AppState;
use actix_web::fs;
use actix_web::http::StatusCode;
use actix_web::HttpRequest;
use actix_web::Path;
use actix_web::Result;
pub fn page_400(_req: &HttpRequest<AppState>) -> Result<fs::NamedFile> {
@@ -19,6 +20,17 @@ pub fn page_404(_req: &HttpRequest) -> Result<fs::NamedFile> {
Ok(fs::NamedFile::open("static/404.html")?.set_status_code(StatusCode::NOT_FOUND))
}
pub fn static_file((path, _req): (Path<String>, HttpRequest)) -> Result<fs::NamedFile> {
trace!("static/{} Triggered!", path);
match fs::NamedFile::open(format!("static/{}", path).as_str()) {
Ok(o) => Ok(o),
Err(_) => {
Ok(fs::NamedFile::open("static/404.html")?.set_status_code(StatusCode::NOT_FOUND))
}
}
}
#[cfg(test)]
mod tests {
use super::*;

View File

@@ -156,6 +156,9 @@ where
})
.boxed(),
App::new()
.resource("/static/{file}", |r| {
r.method(Method::GET).with(default::static_file)
})
.default_resource(|r| {
// 404 for GET request
r.method(Method::GET).f(default::page_404);