]> piware.de Git - learn-rust.git/commitdiff
actix-server: Initial version with /hello/name route
authorMartin Pitt <martin@piware.de>
Fri, 9 Dec 2022 15:15:21 +0000 (16:15 +0100)
committerMartin Pitt <martin@piware.de>
Fri, 9 Dec 2022 20:43:31 +0000 (21:43 +0100)
See https://actix.rs/

actix-server/Cargo.toml [new file with mode: 0644]
actix-server/src/main.rs [new file with mode: 0644]

diff --git a/actix-server/Cargo.toml b/actix-server/Cargo.toml
new file mode 100644 (file)
index 0000000..237dc2e
--- /dev/null
@@ -0,0 +1,10 @@
+[package]
+name = "actix-server"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+actix-web = "4"
+env_logger = "0.9"
diff --git a/actix-server/src/main.rs b/actix-server/src/main.rs
new file mode 100644 (file)
index 0000000..946eb36
--- /dev/null
@@ -0,0 +1,57 @@
+use actix_web::{get, web, App, HttpRequest, HttpServer, Result};
+use actix_web::http::header;
+use actix_web::middleware::Logger;
+
+#[get("/hello/{name}")]
+async fn hello(params: web::Path<String>, req: HttpRequest) -> Result<String> {
+    let name = params.into_inner();
+
+    match req.headers().get(header::USER_AGENT) {
+        Some(agent) => Ok(format!("Hello {} from {}!", name, agent.to_str().unwrap())),
+        None => Ok(format!("Hello {}!", name))
+    }
+}
+
+#[actix_web::main]
+async fn main() -> std::io::Result<()> {
+    env_logger::init_from_env(env_logger::Env::default().default_filter_or("info"));
+
+    HttpServer::new(|| {
+        App::new()
+            .service(hello)
+            .wrap(Logger::default())
+    })
+        .bind(("127.0.0.1", 3030))?
+        .run()
+        .await
+}
+
+#[cfg(test)]
+mod tests {
+    use actix_web::{App, body, test, web};
+    use actix_web::http::header;
+
+    use super::{hello};
+
+    #[actix_web::test]
+    async fn test_hello() {
+        let app = test::init_service(App::new().service(hello)).await;
+
+        // no user-agent
+        let req = test::TestRequest::get().uri("/hello/rust").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 rust!"));
+
+        // with user-agent
+        let req = test::TestRequest::get()
+            .uri("/hello/rust")
+            .insert_header((header::USER_AGENT, "TestBrowser 0.1"))
+            .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 rust from TestBrowser 0.1!"));
+    }
+}