|
| 1 | +#![feature(async_await)] |
| 2 | +#![deny(warnings)] |
| 3 | + |
| 4 | +use std::cell::Cell; |
| 5 | +use std::rc::Rc; |
| 6 | + |
| 7 | +use hyper::{Body, Error, Response, Server}; |
| 8 | +use hyper::service::{make_service_fn, service_fn}; |
| 9 | +use tokio::runtime::current_thread; |
| 10 | + |
| 11 | +// Configure a runtime that runs everything on the current thread, |
| 12 | +// which means it can spawn !Send futures... |
| 13 | +#[hyper::rt::main(single_thread)] |
| 14 | +async fn main() { |
| 15 | + pretty_env_logger::init(); |
| 16 | + |
| 17 | + let addr = ([127, 0, 0, 1], 3000).into(); |
| 18 | + |
| 19 | + // Using a !Send request counter is fine on 1 thread... |
| 20 | + let counter = Rc::new(Cell::new(0)); |
| 21 | + |
| 22 | + let make_service = make_service_fn(move |_| { |
| 23 | + // For each connection, clone the counter to use in our service... |
| 24 | + let cnt = counter.clone(); |
| 25 | + |
| 26 | + async move { |
| 27 | + Ok::<_, Error>(service_fn(move |_| { |
| 28 | + let prev = cnt.get(); |
| 29 | + cnt.set(prev + 1); |
| 30 | + let value = cnt.get(); |
| 31 | + async move { |
| 32 | + Ok::<_, Error>(Response::new(Body::from( |
| 33 | + format!("Request #{}", value) |
| 34 | + ))) |
| 35 | + } |
| 36 | + })) |
| 37 | + } |
| 38 | + }); |
| 39 | + |
| 40 | + // Since the Server needs to spawn some background tasks, we needed |
| 41 | + // to configure an Executor that can spawn !Send futures... |
| 42 | + let exec = current_thread::TaskExecutor::current(); |
| 43 | + |
| 44 | + let server = Server::bind(&addr) |
| 45 | + .executor(exec) |
| 46 | + .serve(make_service); |
| 47 | + |
| 48 | + println!("Listening on http://{}", addr); |
| 49 | + |
| 50 | + // The server would block on current thread to await !Send futures. |
| 51 | + if let Err(e) = server.await { |
| 52 | + eprintln!("server error: {}", e); |
| 53 | + } |
| 54 | +} |
| 55 | + |
0 commit comments