1
0
mirror of https://github.com/actix/examples synced 2024-11-24 06:43:00 +01:00
examples/shutdown-server/src/main.rs

66 lines
1.8 KiB
Rust
Raw Normal View History

use actix_web::{dev::ServerHandle, get, middleware, post, web, App, HttpResponse, HttpServer};
use actix_web_lab::extract::Path;
use parking_lot::Mutex;
2022-07-09 22:08:11 +02:00
2020-01-26 00:49:19 +01:00
#[get("/hello")]
async fn hello() -> &'static str {
"Hello world!"
}
#[post("/stop/{graceful}")]
async fn stop(Path(graceful): Path<bool>, stop_handle: web::Data<StopHandle>) -> HttpResponse {
2022-08-28 19:43:05 +02:00
stop_handle.stop(graceful);
2020-01-26 00:49:19 +01:00
HttpResponse::NoContent().finish()
}
2020-09-12 17:49:45 +02:00
#[actix_web::main]
2020-01-26 00:49:19 +01:00
async fn main() -> std::io::Result<()> {
2022-03-06 01:41:32 +01:00
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
2020-01-26 00:49:19 +01:00
// create the stop handle container
let stop_handle = web::Data::new(StopHandle::default());
2020-01-26 00:49:19 +01:00
2022-03-06 01:41:32 +01:00
log::info!("starting HTTP server at http://localhost:8080");
2020-01-26 00:49:19 +01:00
// start server as normal but don't .await after .run() yet
let srv = HttpServer::new({
let stop_handle = stop_handle.clone();
move || {
// give the server a Sender in .data
App::new()
.app_data(stop_handle.clone())
.service(hello)
.service(stop)
.wrap(middleware::Logger::default())
}
2020-01-26 00:49:19 +01:00
})
2022-03-06 01:41:32 +01:00
.bind(("127.0.0.1", 8080))?
.workers(2)
2020-01-26 00:49:19 +01:00
.run();
// register the server handle with the stop handle
stop_handle.register(srv.handle());
2020-01-26 00:49:19 +01:00
2022-03-06 01:15:16 +01:00
// run server until stopped (either by ctrl-c or stop endpoint)
srv.await
}
#[derive(Default)]
struct StopHandle {
inner: Mutex<Option<ServerHandle>>,
}
impl StopHandle {
/// Sets the server handle to stop.
pub(crate) fn register(&self, handle: ServerHandle) {
*self.inner.lock() = Some(handle);
}
/// Sends stop signal through contained server handle.
pub(crate) fn stop(&self, graceful: bool) {
2022-12-18 18:48:09 +01:00
#[allow(clippy::let_underscore_future)]
let _ = self.inner.lock().as_ref().unwrap().stop(graceful);
}
2020-01-26 00:49:19 +01:00
}