|
| 1 | +#![feature(async_await)] |
| 2 | +#![deny(warnings)] |
| 3 | + |
| 4 | +use std::sync::{Arc, atomic::{AtomicUsize, Ordering}}; |
| 5 | + |
| 6 | +use hyper::{Body, Error, Response, Server}; |
| 7 | +use hyper::service::{make_service_fn, service_fn}; |
| 8 | + |
| 9 | +#[hyper::rt::main] |
| 10 | +async fn main() { |
| 11 | + pretty_env_logger::init(); |
| 12 | + |
| 13 | + let addr = ([127, 0, 0, 1], 3000).into(); |
| 14 | + |
| 15 | + // For the most basic of state, we just share a counter, that increments |
| 16 | + // with each request, and we send its value back in the response. |
| 17 | + let counter = Arc::new(AtomicUsize::new(0)); |
| 18 | + |
| 19 | + // The closure inside `make_service_fn` is run for each connection, |
| 20 | + // creating a 'service' to handle requests for that specific connection. |
| 21 | + let make_service = make_service_fn(move |_| { |
| 22 | + // While the state was moved into the make_service closure, |
| 23 | + // we need to clone it here because this closure is called |
| 24 | + // once for every connection. |
| 25 | + // |
| 26 | + // Each connection could send multiple requests, so |
| 27 | + // the `Service` needs a clone to handle later requests. |
| 28 | + let counter = counter.clone(); |
| 29 | + |
| 30 | + async move { |
| 31 | + // This is the `Service` that will handle the connection. |
| 32 | + // `service_fn` is a helper to convert a function that |
| 33 | + // returns a Response into a `Service`. |
| 34 | + Ok::<_, Error>(service_fn(move |_req| { |
| 35 | + // Get the current count, and also increment by 1, in a single |
| 36 | + // atomic operation. |
| 37 | + let count = counter.fetch_add(1, Ordering::AcqRel); |
| 38 | + async move { |
| 39 | + Ok::<_, Error>( |
| 40 | + Response::new(Body::from(format!("Request #{}", count))) |
| 41 | + ) |
| 42 | + } |
| 43 | + })) |
| 44 | + } |
| 45 | + }); |
| 46 | + |
| 47 | + let server = Server::bind(&addr) |
| 48 | + .serve(make_service); |
| 49 | + |
| 50 | + println!("Listening on http://{}", addr); |
| 51 | + |
| 52 | + if let Err(e) = server.await { |
| 53 | + eprintln!("server error: {}", e); |
| 54 | + } |
| 55 | +} |
| 56 | + |
0 commit comments