|
| 1 | +use std::net::SocketAddr; |
| 2 | + |
| 3 | +use hyper::server::conn::Http; |
| 4 | +use hyper::service::service_fn; |
| 5 | +use hyper::{Body, Method, Request, Response, StatusCode}; |
| 6 | +use tokio::net::TcpListener; |
| 7 | + |
| 8 | +/// This is our service handler. It receives a Request, routes on its |
| 9 | +/// path, and returns a Future of a Response. |
| 10 | +async fn echo(req: Request<Body>) -> Result<Response<Body>, hyper::Error> { |
| 11 | + match (req.method(), req.uri().path()) { |
| 12 | + // Serve some instructions at / |
| 13 | + (&Method::GET, "/") => Ok(Response::new(Body::from( |
| 14 | + "Try POSTing data to /echo such as: `curl localhost:8080/echo -XPOST -d 'hello world'`", |
| 15 | + ))), |
| 16 | + |
| 17 | + // Simply echo the body back to the client. |
| 18 | + (&Method::POST, "/echo") => Ok(Response::new(req.into_body())), |
| 19 | + |
| 20 | + (&Method::POST, "/echo/reversed") => { |
| 21 | + let whole_body = hyper::body::to_bytes(req.into_body()).await?; |
| 22 | + |
| 23 | + let reversed_body = whole_body.iter().rev().cloned().collect::<Vec<u8>>(); |
| 24 | + Ok(Response::new(Body::from(reversed_body))) |
| 25 | + } |
| 26 | + |
| 27 | + // Return the 404 Not Found for other routes. |
| 28 | + _ => { |
| 29 | + let mut not_found = Response::default(); |
| 30 | + *not_found.status_mut() = StatusCode::NOT_FOUND; |
| 31 | + Ok(not_found) |
| 32 | + } |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +#[tokio::main(flavor = "current_thread")] |
| 37 | +async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { |
| 38 | + let addr = SocketAddr::from(([0, 0, 0, 0], 8080)); |
| 39 | + |
| 40 | + let listener = TcpListener::bind(addr).await?; |
| 41 | + println!("Listening on http://{}", addr); |
| 42 | + loop { |
| 43 | + let (stream, _) = listener.accept().await?; |
| 44 | + |
| 45 | + tokio::task::spawn(async move { |
| 46 | + if let Err(err) = Http::new().serve_connection(stream, service_fn(echo)).await { |
| 47 | + println!("Error serving connection: {:?}", err); |
| 48 | + } |
| 49 | + }); |
| 50 | + } |
| 51 | +} |
0 commit comments