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

55 lines
1.7 KiB
Rust
Raw Normal View History

2022-02-18 02:01:48 +00:00
//! Since Actix Web v4, this method is not necessary in order to spawn additional servers alongside
//! your web server since the `Server` object can simply be `spawn`ed. This is kept to illustrate
//! how to run Actix Web from a sync context.
2022-02-02 02:09:06 +00:00
use std::{sync::mpsc, thread, time};
2019-12-25 07:44:33 +04:00
2022-02-02 02:09:06 +00:00
use actix_web::{dev::ServerHandle, middleware, rt, web, App, HttpRequest, HttpServer};
2019-12-25 07:44:33 +04:00
async fn index(req: HttpRequest) -> &'static str {
log::info!("REQ: {req:?}");
2019-12-25 07:44:33 +04:00
"Hello world!"
}
async fn run_app(tx: mpsc::Sender<ServerHandle>) -> std::io::Result<()> {
2022-02-06 08:19:35 +00:00
log::info!("starting HTTP server at http://localhost:8080");
2022-02-02 02:09:06 +00:00
2019-12-25 07:44:33 +04:00
// srv is server controller type, `dev::Server`
let server = HttpServer::new(|| {
2019-12-25 07:44:33 +04:00
App::new()
// enable logger
.wrap(middleware::Logger::default())
.service(web::resource("/index.html").to(|| async { "Hello world!" }))
.service(web::resource("/").to(index))
})
2022-02-02 02:09:06 +00:00
.bind(("127.0.0.1", 8080))?
.workers(2)
2019-12-25 20:48:33 +04:00
.run();
2019-12-25 07:44:33 +04:00
// Send server handle back to the main thread
let _ = tx.send(server.handle());
2022-02-02 02:09:06 +00:00
server.await
2019-12-25 07:44:33 +04:00
}
fn main() {
2022-02-02 02:09:06 +00:00
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
2019-12-25 07:44:33 +04:00
let (tx, rx) = mpsc::channel();
2022-02-02 02:09:06 +00:00
log::info!("spawning thread for server");
2019-12-25 07:44:33 +04:00
thread::spawn(move || {
2022-02-02 02:09:06 +00:00
let server_future = run_app(tx);
rt::System::new().block_on(server_future)
2019-12-25 07:44:33 +04:00
});
let server_handle = rx.recv().unwrap();
2019-12-25 07:44:33 +04:00
2022-02-02 02:09:06 +00:00
log::info!("waiting 10 seconds");
2019-12-25 07:44:33 +04:00
thread::sleep(time::Duration::from_secs(10));
// Send a stop signal to the server, waiting for it to exit gracefully
2022-02-02 02:09:06 +00:00
log::info!("stopping server");
rt::System::new().block_on(server_handle.stop(true));
2019-12-25 07:44:33 +04:00
}