1
0
mirror of https://github.com/actix/examples synced 2024-12-03 18:22:14 +01:00
examples/basics/run-in-thread/src/main.rs

50 lines
1.4 KiB
Rust
Raw Normal View History

2019-12-25 04:44:33 +01:00
use std::sync::mpsc;
use std::{thread, time};
use actix_web::dev::ServerHandle;
use actix_web::{middleware, rt, web, App, HttpRequest, HttpServer};
2019-12-25 04:44:33 +01:00
async fn index(req: HttpRequest) -> &'static str {
log::info!("REQ: {:?}", req);
2019-12-25 04:44:33 +01:00
"Hello world!"
}
async fn run_app(tx: mpsc::Sender<ServerHandle>) -> std::io::Result<()> {
2019-12-25 04:44:33 +01:00
// srv is server controller type, `dev::Server`
let server = HttpServer::new(|| {
2019-12-25 04:44:33 +01:00
App::new()
// enable logger
.wrap(middleware::Logger::default())
.service(web::resource("/index.html").to(|| async { "Hello world!" }))
.service(web::resource("/").to(index))
})
.bind("127.0.0.1:8080")?
2019-12-25 17:48:33 +01:00
.run();
2019-12-25 04:44:33 +01:00
// Send server handle back to the main thread
let _ = tx.send(server.handle());
server.await
2019-12-25 04:44:33 +01:00
}
fn main() {
std::env::set_var("RUST_LOG", "actix_web=info,actix_server=trace");
env_logger::init();
let (tx, rx) = mpsc::channel();
log::info!("START SERVER");
2019-12-25 04:44:33 +01:00
thread::spawn(move || {
let future = run_app(tx);
rt::System::new().block_on(future)
2019-12-25 04:44:33 +01:00
});
let server_handle = rx.recv().unwrap();
2019-12-25 04:44:33 +01:00
log::info!("WAITING 10 SECONDS");
2019-12-25 04:44:33 +01:00
thread::sleep(time::Duration::from_secs(10));
log::info!("STOPPING SERVER");
// Send a stop signal to the server, waiting for it to exit gracefully
rt::System::new().block_on(server_handle.stop(true));
2019-12-25 04:44:33 +01:00
}