From: Martin Pitt Date: Fri, 9 Dec 2022 15:15:21 +0000 (+0100) Subject: actix-server: Initial version with /hello/name route X-Git-Url: https://piware.de/gitweb/?a=commitdiff_plain;h=577248e40bb772480fb036fe2deafc1ac2a11354;p=learn-rust.git actix-server: Initial version with /hello/name route See https://actix.rs/ --- diff --git a/actix-server/Cargo.toml b/actix-server/Cargo.toml new file mode 100644 index 0000000..237dc2e --- /dev/null +++ b/actix-server/Cargo.toml @@ -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 index 0000000..946eb36 --- /dev/null +++ b/actix-server/src/main.rs @@ -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, req: HttpRequest) -> Result { + 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!")); + } +}