mirror of
https://github.com/actix/examples
synced 2024-12-03 18:22:14 +01:00
53 lines
1.3 KiB
Rust
53 lines
1.3 KiB
Rust
|
use std::sync::mpsc;
|
||
|
use std::{thread, time};
|
||
|
|
||
|
use actix_rt::System;
|
||
|
use actix_web::{dev::Server, middleware, web, App, HttpRequest, HttpServer};
|
||
|
|
||
|
async fn index(req: HttpRequest) -> &'static str {
|
||
|
println!("REQ: {:?}", req);
|
||
|
"Hello world!"
|
||
|
}
|
||
|
|
||
|
fn run_app(tx: mpsc::Sender<Server>) -> std::io::Result<()> {
|
||
|
let mut sys = System::new("test");
|
||
|
|
||
|
// 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")?
|
||
|
.start();
|
||
|
|
||
|
// 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!("WATING 10 SECONDS");
|
||
|
thread::sleep(time::Duration::from_secs(10));
|
||
|
|
||
|
println!("STOPPING SERVER");
|
||
|
// init stop server and wait until server gracefully exit
|
||
|
System::new("").block_on(srv.stop(true));
|
||
|
}
|