2020-01-31 13:10:56 +01:00
|
|
|
use actix_web::{get, middleware, post, web, App, HttpResponse, HttpServer};
|
2020-01-26 00:49:19 +01:00
|
|
|
use futures::executor;
|
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()
|
|
|
|
}
|
|
|
|
|
|
|
|
#[actix_rt::main]
|
|
|
|
async fn main() -> std::io::Result<()> {
|
|
|
|
std::env::set_var("RUST_LOG", "actix_server=debug,actix_web=debug");
|
|
|
|
env_logger::init();
|
|
|
|
|
|
|
|
// create a channel
|
|
|
|
let (tx, rx) = mpsc::channel::<()>();
|
2020-04-03 09:14:30 +02:00
|
|
|
let _stopper = tx.clone();
|
2020-01-26 00:49:19 +01:00
|
|
|
|
|
|
|
let bind = "127.0.0.1:8080";
|
|
|
|
|
|
|
|
// start server as normal but don't .await after .run() yet
|
|
|
|
let server = HttpServer::new(move || {
|
|
|
|
// give the server a Sender in .data
|
|
|
|
let stopper = tx.clone();
|
|
|
|
|
|
|
|
App::new()
|
|
|
|
.data(stopper)
|
|
|
|
.wrap(middleware::Logger::default())
|
|
|
|
.service(hello)
|
|
|
|
.service(stop)
|
|
|
|
})
|
|
|
|
.bind(&bind)?
|
|
|
|
.run();
|
|
|
|
|
|
|
|
// clone the Server handle
|
|
|
|
let srv = server.clone();
|
|
|
|
thread::spawn(move || {
|
|
|
|
// wait for shutdown signal
|
|
|
|
rx.recv().unwrap();
|
|
|
|
|
|
|
|
// stop server gracefully
|
|
|
|
executor::block_on(srv.stop(true))
|
|
|
|
});
|
|
|
|
|
|
|
|
// run server
|
|
|
|
server.await
|
|
|
|
}
|