axum-server: Serve whole directory
[learn-rust.git] / hyper-server / src / main.rs
1 use std::convert::Infallible;
2 use std::net::SocketAddr;
3
4 use hyper::service::{make_service_fn, service_fn};
5 use hyper::{Body, Request, Response, Server, Method, StatusCode};
6
7 async fn service(req: Request<Body>) -> Result<Response<Body>, Infallible> {
8     let mut response = Response::new(Body::empty());
9
10     match (req.method(), req.uri().path()) {
11         (&Method::GET, "/") => {
12             *response.body_mut() = Body::from("Try POSTing data to /echo");
13         },
14         (&Method::POST, "/echo") => {
15              *response.body_mut() = req.into_body();
16         },
17         _ => {
18             *response.status_mut() = StatusCode::NOT_FOUND;
19         }
20     }
21
22     Ok(response)
23 }
24
25 #[tokio::main]
26 async fn main() {
27     // We'll bind to 127.0.0.1:3000
28     let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
29     let make_svc = make_service_fn(|_conn| async {
30         Ok::<_, Infallible>(service_fn(service))
31     });
32     let server = Server::bind(&addr).serve(make_svc);
33     let graceful = server.with_graceful_shutdown(async {
34         tokio::signal::ctrl_c()
35         .await
36         .expect("failed to install CTRL+C signal handler");
37     });
38
39     if let Err(e) = graceful.await {
40         eprintln!("server error: {}", e);
41     }
42 }