1
0
mirror of https://github.com/actix/examples synced 2025-02-02 09:39:03 +01:00

52 lines
1.6 KiB
Rust
Raw Normal View History

2022-12-17 22:10:51 +00:00
use std::time::Duration;
use actix_http::body::MessageBody;
use actix_web::{dev, rt::time, web, App, Error, HttpServer};
use actix_web_lab::middleware::{from_fn, Next};
2018-07-09 20:18:31 +02:00
mod read_request_body;
mod read_response_body;
2019-12-07 23:59:24 +06:00
mod redirect;
2018-07-09 20:18:31 +02:00
mod simple;
2022-12-17 22:10:51 +00:00
// See more examples of from_fn middleware here:
// https://github.com/robjtede/actix-web-lab/blob/main/actix-web-lab/examples/from_fn.rs
async fn timeout_10secs(
req: dev::ServiceRequest,
next: Next<impl MessageBody + 'static>,
) -> Result<dev::ServiceResponse<impl MessageBody>, Error> {
match time::timeout(Duration::from_secs(10), next.call(req)).await {
Ok(res) => res,
Err(_err) => Err(actix_web::error::ErrorRequestTimeout("")),
}
}
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<()> {
2022-02-22 12:12:17 +00:00
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
log::info!("starting HTTP server at http://localhost:8080");
2018-07-09 20:18:31 +02:00
2019-03-10 19:19:50 -07:00
HttpServer::new(|| {
2018-07-09 20:18:31 +02:00
App::new()
2019-03-26 04:29:00 +01:00
.wrap(redirect::CheckLogin)
.wrap(read_request_body::Logging)
.wrap(read_response_body::Logging)
2019-03-26 04:29:00 +01:00
.wrap(simple::SayHi)
2022-12-17 22:10:51 +00:00
.wrap(from_fn(timeout_10secs))
.service(web::resource("/login").to(|body: String| async move {
println!("request body (handler): {body}");
2020-01-31 07:21:39 -05:00
"You are on /login. Go to src/redirect.rs to change this behavior."
2019-12-07 23:59:24 +06:00
}))
2022-02-18 02:44:02 +00:00
.service(
web::resource("/").to(|| async {
"Hello, middleware! Check the console where the server is run."
}),
)
2019-03-09 18:03:09 -08:00
})
2022-02-17 20:22:36 +00:00
.bind(("127.0.0.1", 8080))?
.workers(1)
2019-12-25 20:48:33 +04:00
.run()
2019-12-07 23:59:24 +06:00
.await
2018-07-09 20:18:31 +02:00
}