From: Martin Pitt Date: Sun, 18 Sep 2022 18:28:53 +0000 (+0200) Subject: hyper-server: Initial version X-Git-Url: https://piware.de/gitweb/?a=commitdiff_plain;h=8a185a1213d5ad2d53df30bac8cfb1987a5cff9f;p=learn-rust.git hyper-server: Initial version --- diff --git a/hyper-server/Cargo.toml b/hyper-server/Cargo.toml new file mode 100644 index 0000000..0d9bdfe --- /dev/null +++ b/hyper-server/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "hyper-server" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +futures = "0.3" +hyper = { version = "0.14", features = ["server", "runtime", "http1"] } +tokio = { version = "1", features = ["full"] } diff --git a/hyper-server/src/main.rs b/hyper-server/src/main.rs new file mode 100644 index 0000000..8199471 --- /dev/null +++ b/hyper-server/src/main.rs @@ -0,0 +1,42 @@ +use std::convert::Infallible; +use std::net::SocketAddr; + +use hyper::service::{make_service_fn, service_fn}; +use hyper::{Body, Request, Response, Server, Method, StatusCode}; + +async fn service(req: Request) -> Result, Infallible> { + let mut response = Response::new(Body::empty()); + + match (req.method(), req.uri().path()) { + (&Method::GET, "/") => { + *response.body_mut() = Body::from("Try POSTing data to /echo"); + }, + (&Method::POST, "/echo") => { + *response.body_mut() = req.into_body(); + }, + _ => { + *response.status_mut() = StatusCode::NOT_FOUND; + } + } + + Ok(response) +} + +#[tokio::main] +async fn main() { + // We'll bind to 127.0.0.1:3000 + let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); + let make_svc = make_service_fn(|_conn| async { + Ok::<_, Infallible>(service_fn(service)) + }); + let server = Server::bind(&addr).serve(make_svc); + let graceful = server.with_graceful_shutdown(async { + tokio::signal::ctrl_c() + .await + .expect("failed to install CTRL+C signal handler"); + }); + + if let Err(e) = graceful.await { + eprintln!("server error: {}", e); + } +}