1
0
mirror of https://github.com/actix/examples synced 2024-12-01 01:24:35 +01:00
examples/hello-world/src/main.rs

51 lines
1.3 KiB
Rust
Raw Normal View History

2019-03-10 07:38:15 +01:00
use actix_web::{middleware, web, App, HttpRequest, HttpServer};
2019-12-07 18:59:24 +01:00
async fn index(req: HttpRequest) -> &'static str {
2019-03-10 07:38:15 +01:00
println!("REQ: {:?}", req);
"Hello world!"
}
2019-12-07 18:59:24 +01:00
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
2019-03-10 07:38:15 +01:00
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
2019-03-10 07:38:15 +01:00
HttpServer::new(|| {
2018-05-08 20:08:43 +02:00
App::new()
// enable logger
2019-03-26 04:29:00 +01:00
.wrap(middleware::Logger::default())
2019-12-07 18:59:24 +01:00
.service(web::resource("/index.html").to(|| async { "Hello world!" }))
2019-03-10 07:38:15 +01:00
.service(web::resource("/").to(index))
2019-03-10 03:03:09 +01:00
})
2019-03-10 07:38:15 +01:00
.bind("127.0.0.1:8080")?
2019-12-25 17:48:33 +01:00
.run()
2019-12-07 18:59:24 +01:00
.await
}
#[cfg(test)]
mod tests {
use super::*;
use actix_web::dev::Service;
2019-12-07 18:59:24 +01:00
use actix_web::{http, test, web, App, Error};
2019-12-07 18:59:24 +01:00
#[actix_rt::test]
async fn test_index() -> Result<(), Error> {
let app = App::new().route("/", web::get().to(index));
2019-12-07 18:59:24 +01:00
let mut app = test::init_service(app).await;
2019-12-07 18:59:24 +01:00
let req = test::TestRequest::get().uri("/").to_request();
let resp = app.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::OK);
let response_body = match resp.response().body().as_ref() {
Some(actix_web::body::Body::Bytes(bytes)) => bytes,
_ => panic!("Response error"),
};
assert_eq!(response_body, r##"Hello world!"##);
Ok(())
}
}