]> piware.de Git - learn-rust.git/commitdiff
actix-server: Add static directory route
authorMartin Pitt <martin@piware.de>
Fri, 9 Dec 2022 20:58:53 +0000 (21:58 +0100)
committerMartin Pitt <martin@piware.de>
Fri, 9 Dec 2022 20:58:53 +0000 (21:58 +0100)
actix-server/Cargo.toml
actix-server/src/main.rs

index 237dc2e705913f73dbce9769ff7376585982d153..fa315f9210f5f77676e42fb59146baf82b4aa763 100644 (file)
@@ -7,4 +7,5 @@ edition = "2021"
 
 [dependencies]
 actix-web = "4"
+actix-files = "0.6"
 env_logger = "0.9"
index 946eb36fc0c466fdd424d1c1ff9dba23676c8229..ae2b22315a4b3be0537a30983e835eaecf2148f1 100644 (file)
@@ -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);
+    }
 }