From a26154d98eccc634e1fea992b20678903c1e0e46 Mon Sep 17 00:00:00 2001 From: tottoto Date: Wed, 7 Aug 2024 04:50:37 +0900 Subject: [PATCH 1/2] use let-else statement for error handling --- examples/hyper.rs | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/examples/hyper.rs b/examples/hyper.rs index e7d9849..71dab27 100644 --- a/examples/hyper.rs +++ b/examples/hyper.rs @@ -43,27 +43,23 @@ type Router = HashMap>; async fn route(router: Arc, req: Request) -> hyper::Result> { // find the subrouter for this request method - let router = match router.get(req.method()) { - Some(router) => router, + let Some(router) = router.get(req.method()) else { // if there are no routes for this method, respond with 405 Method Not Allowed - None => { - return Ok(Response::builder() - .status(405) - .body(Body::default()) - .unwrap()) - } + return Ok(Response::builder() + .status(405) + .body(Body::default()) + .unwrap()); }; // find the service for this request path - match router.at(req.uri().path()) { - Ok(found) => { - // lock the service for a very short time, just to clone the service - let mut service = found.value.lock().unwrap().clone(); - service.call(req).await - } + let Ok(found) = router.at(req.uri().path()) else { // if we there is no matching service, call the 404 handler - Err(_) => not_found(req).await, - } + return not_found(req).await; + }; + + // lock the service for a very short time, just to clone the service + let mut service = found.value.lock().unwrap().clone(); + service.call(req).await } #[tokio::main] From c9229668e58f0f846163a583a4a4d6a285334ff6 Mon Sep 17 00:00:00 2001 From: tottoto Date: Wed, 7 Aug 2024 05:02:53 +0900 Subject: [PATCH 2/2] use StatusCode to describe http status code --- examples/hyper.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/hyper.rs b/examples/hyper.rs index 71dab27..8bd229c 100644 --- a/examples/hyper.rs +++ b/examples/hyper.rs @@ -4,7 +4,7 @@ use std::sync::{Arc, Mutex}; use http_body_util::Full; use hyper::body::{Bytes, Incoming}; use hyper::server::conn::http1::Builder as ConnectionBuilder; -use hyper::{Method, Request, Response}; +use hyper::{Method, Request, Response, StatusCode}; use hyper_util::rt::TokioIo; use tokio::net::TcpListener; use tower::service_fn; @@ -26,7 +26,7 @@ async fn blog(_req: Request) -> hyper::Result> { // 404 handler async fn not_found(_req: Request) -> hyper::Result> { Ok(Response::builder() - .status(404) + .status(StatusCode::NOT_FOUND) .body(Body::default()) .unwrap()) } @@ -46,7 +46,7 @@ async fn route(router: Arc, req: Request) -> hyper::Result