2020-01-31 13:10:56 +01:00
|
|
|
use actix_web::{get, middleware, post, web, App, HttpResponse, HttpServer};
|
2020-01-31 13:21:39 +01:00
|
|
|
use std::{sync::mpsc, thread};
|
2020-02-12 13:53:01 +01:00
|
|
|
|
2020-01-26 00:49:19 +01:00
|
|
|
#[get("/hello")]
|
|
|
|
async fn hello() -> &'static str {
|
|
|
|
"Hello world!"
|
|
|
|
}
|
|
|
|
|
|
|
|
#[post("/stop")]
|
|
|
|
async fn stop(stopper: web::Data<mpsc::Sender<()>>) -> HttpResponse {
|
|
|
|
// make request that sends message through the Sender
|
|
|
|
stopper.send(()).unwrap();
|
|
|
|
|
|
|
|
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 a channel
|
|
|
|
let (tx, rx) = mpsc::channel::<()>();
|
|
|
|
|
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 server = HttpServer::new(move || {
|
|
|
|
// give the server a Sender in .data
|
|
|
|
App::new()
|
2022-01-29 16:24:04 +01:00
|
|
|
.app_data(web::Data::new(tx.clone()))
|
2020-01-26 00:49:19 +01:00
|
|
|
.wrap(middleware::Logger::default())
|
|
|
|
.service(hello)
|
|
|
|
.service(stop)
|
|
|
|
})
|
2022-03-06 01:41:32 +01:00
|
|
|
.bind(("127.0.0.1", 8080))?
|
2020-01-26 00:49:19 +01:00
|
|
|
.run();
|
|
|
|
|
2022-03-06 01:15:16 +01:00
|
|
|
// clone the server handle
|
2022-01-29 16:24:04 +01:00
|
|
|
let srv = server.handle();
|
2020-01-26 00:49:19 +01:00
|
|
|
thread::spawn(move || {
|
|
|
|
// wait for shutdown signal
|
|
|
|
rx.recv().unwrap();
|
|
|
|
|
2022-03-06 01:15:16 +01:00
|
|
|
// send stop server gracefully command
|
|
|
|
srv.stop(true)
|
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)
|
2020-01-26 00:49:19 +01:00
|
|
|
server.await
|
|
|
|
}
|