]> piware.de Git - learn-rust.git/commitdiff
hyper-server: Initial version
authorMartin Pitt <martin@piware.de>
Sun, 18 Sep 2022 18:28:53 +0000 (20:28 +0200)
committerMartin Pitt <martin@piware.de>
Mon, 19 Sep 2022 06:59:29 +0000 (08:59 +0200)
hyper-server/Cargo.toml [new file with mode: 0644]
hyper-server/src/main.rs [new file with mode: 0644]

diff --git a/hyper-server/Cargo.toml b/hyper-server/Cargo.toml
new file mode 100644 (file)
index 0000000..0d9bdfe
--- /dev/null
@@ -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 (file)
index 0000000..8199471
--- /dev/null
@@ -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<Body>) -> Result<Response<Body>, 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);
+    }
+}