|
| 1 | +// Credit: Ben Ajaero |
| 2 | + |
| 3 | +use std::convert::Infallible; |
| 4 | +use std::net::TcpListener; |
| 5 | +use std::sync::Arc; |
| 6 | + |
| 7 | +use http::Method; |
| 8 | +use hyper::service::{make_service_fn, service_fn}; |
| 9 | +use hyper::{Body, Request as HyperRequest, Response as HyperResponse, Server}; |
| 10 | + |
| 11 | +use crate::error::RawError; |
| 12 | +use crate::middleware::{handler, middleware, Middleware, Next}; |
| 13 | +use crate::request::Request; |
| 14 | +use crate::response::Response; |
| 15 | +use crate::router::Router; |
| 16 | + |
| 17 | +pub struct App { |
| 18 | + router: Router, |
| 19 | + middleware: Vec<Middleware>, |
| 20 | +} |
| 21 | + |
| 22 | +impl App { |
| 23 | + pub fn new() -> Self { |
| 24 | + Self { |
| 25 | + router: Router::new(), |
| 26 | + middleware: Vec::new(), |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + pub fn get<F, Fut>(&mut self, path: &str, handler_fn: F) |
| 31 | + where |
| 32 | + F: Fn(Request) -> Fut + Send + Sync + 'static, |
| 33 | + Fut: std::future::Future<Output = Response> + Send + 'static, |
| 34 | + { |
| 35 | + self.route(Method::GET, path, handler_fn); |
| 36 | + } |
| 37 | + |
| 38 | + pub fn post<F, Fut>(&mut self, path: &str, handler_fn: F) |
| 39 | + where |
| 40 | + F: Fn(Request) -> Fut + Send + Sync + 'static, |
| 41 | + Fut: std::future::Future<Output = Response> + Send + 'static, |
| 42 | + { |
| 43 | + self.route(Method::POST, path, handler_fn); |
| 44 | + } |
| 45 | + |
| 46 | + pub fn route<F, Fut>(&mut self, method: Method, path: &str, handler_fn: F) |
| 47 | + where |
| 48 | + F: Fn(Request) -> Fut + Send + Sync + 'static, |
| 49 | + Fut: std::future::Future<Output = Response> + Send + 'static, |
| 50 | + { |
| 51 | + let wrapped = handler(handler_fn); |
| 52 | + self.router.add(method, path, wrapped); |
| 53 | + } |
| 54 | + |
| 55 | + pub fn add_middleware<F, Fut>(&mut self, middleware_fn: F) |
| 56 | + where |
| 57 | + F: Fn(Request, Next) -> Fut + Send + Sync + 'static, |
| 58 | + Fut: std::future::Future<Output = Response> + Send + 'static, |
| 59 | + { |
| 60 | + self.middleware.push(middleware(middleware_fn)); |
| 61 | + } |
| 62 | + |
| 63 | + pub async fn listen(self, addr: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { |
| 64 | + let listener = TcpListener::bind(addr).map_err(|err| { |
| 65 | + eprintln!("Failed to bind {}: {}", addr, err); |
| 66 | + err |
| 67 | + })?; |
| 68 | + self.serve(listener).await |
| 69 | + } |
| 70 | + |
| 71 | + pub async fn serve( |
| 72 | + self, |
| 73 | + listener: TcpListener, |
| 74 | + ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { |
| 75 | + listener |
| 76 | + .set_nonblocking(true) |
| 77 | + .map_err(|err| { |
| 78 | + eprintln!("Failed to set non-blocking: {}", err); |
| 79 | + err |
| 80 | + })?; |
| 81 | + |
| 82 | + let state = Arc::new(self); |
| 83 | + let make_svc = make_service_fn(move |_| { |
| 84 | + let state = Arc::clone(&state); |
| 85 | + async move { |
| 86 | + Ok::<_, Infallible>(service_fn(move |req| { |
| 87 | + let state = Arc::clone(&state); |
| 88 | + async move { state.handle(req).await } |
| 89 | + })) |
| 90 | + } |
| 91 | + }); |
| 92 | + |
| 93 | + Ok(Server::from_tcp(listener)?.serve(make_svc).await?) |
| 94 | + } |
| 95 | + |
| 96 | + async fn handle(self: Arc<Self>, req: HyperRequest<Body>) -> Result<HyperResponse<Body>, Infallible> { |
| 97 | + let method = req.method().clone(); |
| 98 | + let path = req.uri().path().to_string(); |
| 99 | + |
| 100 | + let response = if let Some(route_match) = self.router.find(&method, &path) { |
| 101 | + let request = Request::new(req, route_match.params); |
| 102 | + let handler = route_match.handler; |
| 103 | + let middleware = Arc::new(self.middleware.clone()); |
| 104 | + let next = Next::new(middleware, handler); |
| 105 | + next.run(request).await |
| 106 | + } else if self.router.allows_path(&path) { |
| 107 | + RawError::MethodNotAllowed.into_response() |
| 108 | + } else { |
| 109 | + RawError::NotFound.into_response() |
| 110 | + }; |
| 111 | + |
| 112 | + Ok(response.into_inner()) |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +#[cfg(test)] |
| 117 | +mod tests { |
| 118 | + use super::App; |
| 119 | + use crate::response::{Response, Text}; |
| 120 | + |
| 121 | + #[tokio::test] |
| 122 | + async fn app_registers_route() { |
| 123 | + let mut app = App::new(); |
| 124 | + app.get("/", |_req| async { Response::from(Text::new("ok")) }); |
| 125 | + assert!(app.router.find(&http::Method::GET, "/").is_some()); |
| 126 | + } |
| 127 | +} |
0 commit comments