1
0
mirror of https://github.com/actix/examples synced 2025-01-23 06:14:35 +01:00

44 lines
1.6 KiB
Rust
Raw Normal View History

2022-10-16 19:24:17 +01:00
use actix_web::{web, App, HttpResponse, HttpServer};
2020-06-22 21:16:25 +08:00
2020-09-12 16:49:45 +01:00
#[actix_web::main]
2020-06-22 21:16:25 +08:00
async fn main() -> std::io::Result<()> {
2022-10-16 19:24:17 +01:00
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
2022-10-16 19:24:17 +01:00
log::info!("starting HTTP server at http://localhost:8080");
2020-06-22 21:16:25 +08:00
HttpServer::new(move || {
App::new()
// a dummy data_factory implementation
.data_factory(|| {
2022-10-16 19:24:17 +01:00
// App::data_factory would accept a future as return type and poll the future when
// App is initialized.
//
// The Output of the future must be Result<T, E> and T will be the transformed to
// App::Data<T> that can be extracted from handler/request. (The E will only be used
// to trigger an error log.)
//
// This data is bound to worker thread and you get an instance of it for each worker
// of the HttpServer, hence the name data_factory.
//
// It is NOT shared between workers
// (unless the underlying data is a smart pointer like Arc<T>).
2020-06-22 21:16:25 +08:00
async {
2022-10-16 19:24:17 +01:00
// would be transformed into Data<usize>
Ok::<_, ()>(123_usize)
2020-06-22 21:16:25 +08:00
}
})
2022-10-16 19:24:17 +01:00
.route(
"/",
web::to(|data: web::Data<usize>| async move {
assert_eq!(**data, 123);
2022-10-16 21:36:23 +01:00
HttpResponse::NoContent().finish()
2022-10-16 19:24:17 +01:00
}),
)
2020-06-22 21:16:25 +08:00
})
2022-10-16 19:24:17 +01:00
.workers(2)
2022-02-17 20:22:36 +00:00
.bind(("127.0.0.1", 8080))?
2020-06-22 21:16:25 +08:00
.run()
.await
}