1
0
mirror of https://github.com/actix/examples synced 2025-02-13 05:52:20 +01:00

48 lines
1.3 KiB
Rust
Raw Normal View History

2019-03-09 22:38:15 -08:00
use actix_web::{middleware, web, App, HttpRequest, HttpServer};
2019-12-07 23:59:24 +06:00
async fn index(req: HttpRequest) -> &'static str {
println!("REQ: {req:?}");
"Hello world!"
}
2020-09-12 16:49:45 +01:00
#[actix_web::main]
2019-12-07 23:59:24 +06:00
async fn main() -> std::io::Result<()> {
2023-03-14 03:11:49 +00:00
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
log::info!("starting HTTP server at http://localhost:8080");
2019-03-09 22:38:15 -08:00
HttpServer::new(|| {
2018-05-08 11:08:43 -07:00
App::new()
// enable logger
2019-03-26 04:29:00 +01:00
.wrap(middleware::Logger::default())
2019-12-07 23:59:24 +06:00
.service(web::resource("/index.html").to(|| async { "Hello world!" }))
2019-03-09 22:38:15 -08:00
.service(web::resource("/").to(index))
2019-03-09 18:03:09 -08:00
})
2022-02-17 20:22:36 +00:00
.bind(("127.0.0.1", 8080))?
2019-12-25 20:48:33 +04:00
.run()
2019-12-07 23:59:24 +06:00
.await
}
#[cfg(test)]
mod tests {
2024-02-20 03:29:10 +00:00
use actix_web::{body::to_bytes, dev::Service, http, test, Error};
2022-07-09 21:08:11 +01:00
use super::*;
#[actix_web::test]
2019-12-07 23:59:24 +06:00
async fn test_index() -> Result<(), Error> {
let app = App::new().route("/", web::get().to(index));
let app = test::init_service(app).await;
2019-12-07 23:59:24 +06:00
let req = test::TestRequest::get().uri("/").to_request();
let resp = app.call(req).await?;
assert_eq!(resp.status(), http::StatusCode::OK);
let response_body = resp.into_body();
assert_eq!(to_bytes(response_body).await?, r##"Hello world!"##);
Ok(())
}
}