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

52 lines
1.3 KiB
Rust
Raw Normal View History

2019-12-25 04:44:33 +01:00
use std::sync::mpsc;
use std::{thread, time};
2020-09-12 17:49:45 +02:00
use actix_web::{dev::Server, middleware, rt, web, App, HttpRequest, HttpServer};
2019-12-25 04:44:33 +01:00
async fn index(req: HttpRequest) -> &'static str {
println!("REQ: {:?}", req);
"Hello world!"
}
fn run_app(tx: mpsc::Sender<Server>) -> std::io::Result<()> {
2020-09-12 17:49:45 +02:00
let mut sys = rt::System::new("test");
2019-12-25 04:44:33 +01:00
// srv is server controller type, `dev::Server`
let srv = HttpServer::new(|| {
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 controller to main thread
let _ = tx.send(srv.clone());
// run future
sys.block_on(srv)
}
fn main() {
std::env::set_var("RUST_LOG", "actix_web=info,actix_server=trace");
env_logger::init();
let (tx, rx) = mpsc::channel();
println!("START SERVER");
thread::spawn(move || {
let _ = run_app(tx);
});
let srv = rx.recv().unwrap();
println!("WAITING 10 SECONDS");
2019-12-25 04:44:33 +01:00
thread::sleep(time::Duration::from_secs(10));
println!("STOPPING SERVER");
// init stop server and wait until server gracefully exit
2020-09-12 17:49:45 +02:00
rt::System::new("").block_on(srv.stop(true));
2019-12-25 04:44:33 +01:00
}