From 9bcb2f272943c88dd3cafe1f5679fcd3a20a89a9 Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Fri, 9 Dec 2022 21:58:53 +0100 Subject: [PATCH] actix-server: Add static directory route --- actix-server/Cargo.toml | 1 + actix-server/src/main.rs | 29 ++++++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/actix-server/Cargo.toml b/actix-server/Cargo.toml index 237dc2e..fa315f9 100644 --- a/actix-server/Cargo.toml +++ b/actix-server/Cargo.toml @@ -7,4 +7,5 @@ edition = "2021" [dependencies] actix-web = "4" +actix-files = "0.6" env_logger = "0.9" diff --git a/actix-server/src/main.rs b/actix-server/src/main.rs index 946eb36..ae2b223 100644 --- a/actix-server/src/main.rs +++ b/actix-server/src/main.rs @@ -19,6 +19,7 @@ async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .service(hello) + .service(actix_files::Files::new("/dir", "../static")) .wrap(Logger::default()) }) .bind(("127.0.0.1", 3030))? @@ -29,12 +30,13 @@ async fn main() -> std::io::Result<()> { #[cfg(test)] mod tests { use actix_web::{App, body, test, web}; - use actix_web::http::header; + use actix_web::http::{header, StatusCode}; use super::{hello}; #[actix_web::test] async fn test_hello() { + // FIXME: duplicating the .service() call from main() here is super ugly, but it's hard to move that into a fn let app = test::init_service(App::new().service(hello)).await; // no user-agent @@ -54,4 +56,29 @@ mod tests { assert_eq!(body::to_bytes(res.into_body()).await.unwrap(), web::Bytes::from_static(b"Hello rust from TestBrowser 0.1!")); } + + #[actix_web::test] + async fn test_static_dir() { + // FIXME: duplicating the .service() call from main() here is super ugly, but it's hard to move that into a fn + let app = test::init_service(App::new().service(actix_files::Files::new("/dir", "../static"))).await; + + let req = test::TestRequest::get().uri("/dir/plain.txt").to_request(); + let res = test::call_service(&app, req).await; + assert!(res.status().is_success()); + assert_eq!(body::to_bytes(res.into_body()).await.unwrap(), + web::Bytes::from_static(b"Hello world! This is uncompressed text.\n")); + + // subdir + let req = test::TestRequest::get().uri("/dir/dir1/optzip.txt").to_request(); + let res = test::call_service(&app, req).await; + assert!(res.status().is_success()); + assert_eq!(body::to_bytes(res.into_body()).await.unwrap(), + web::Bytes::from_static(b"This file is available uncompressed or compressed\n\ + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n")); + + // does not support transparent decompression + let req = test::TestRequest::get().uri("/dir/onlycompressed.txt").to_request(); + let res = test::call_service(&app, req).await; + assert_eq!(res.status(), StatusCode::NOT_FOUND); + } } -- 2.39.2