micro_http/handler/mod.rs
1//! HTTP request handler module
2//!
3//! This module provides traits and utilities for handling HTTP requests. It defines
4//! the core abstraction for request processing through the [`Handler`] trait and
5//! provides utilities for creating handlers from async functions.
6//!
7//! # Examples
8//!
9//! ```no_run
10//! use micro_http::handler::{Handler, make_handler};
11//! use micro_http::protocol::body::ReqBody;
12//! use http::{Request, Response};
13//! use std::error::Error;
14//!
15//! // Define an async handler function
16//! async fn hello_handler(req: Request<ReqBody>) -> Result<Response<String>, Box<dyn Error + Send + Sync>> {
17//! Ok(Response::new("Hello World!".to_string()))
18//! }
19//!
20//! // Create a handler from the function
21//! let handler = make_handler(hello_handler);
22//! ```
23
24use crate::protocol::body::ReqBody;
25use http::{Request, Response};
26use http_body::Body;
27use std::error::Error;
28
29/// A trait for handling HTTP requests
30///
31/// This trait defines the core interface for processing HTTP requests and generating responses.
32/// Implementors of this trait can be used to handle requests in the HTTP server.
33///
34/// # Type Parameters
35///
36/// * `RespBody`: The response body type that implements [`Body`]
37/// * `Error`: The error type that can be converted into a boxed error
38/// * `Fut`: The future type returned by the handler
39#[trait_variant::make(Send)]
40pub trait Handler: Sync {
41 /// The type of the response body
42 type RespBody: Body;
43
44 /// The error type returned by the handler
45 type Error: Into<Box<dyn Error + Send + Sync>>;
46
47 async fn call(&self, req: Request<ReqBody>) -> Result<Response<Self::RespBody>, Self::Error>;
48}
49
50/// A wrapper type for function-based handlers
51///
52/// This type implements [`Handler`] for functions that take a [`Request`] and
53/// return a [`Future`] resolving to a [`Response`].
54#[derive(Debug)]
55pub struct HandlerFn<F> {
56 f: F,
57}
58
59impl<RespBody, Err, F, Fut> Handler for HandlerFn<F>
60where
61 RespBody: Body,
62 F: Fn(Request<ReqBody>) -> Fut + Send + Sync,
63 Err: Into<Box<dyn Error + Send + Sync>>,
64 Fut: Future<Output = Result<Response<RespBody>, Err>> + Send,
65{
66 type RespBody = RespBody;
67 type Error = Err;
68
69 async fn call(&self, req: Request<ReqBody>) -> Result<Response<Self::RespBody>, Self::Error> {
70 (self.f)(req).await
71 }
72}
73
74/// Creates a new handler from an async function
75///
76/// This function wraps an async function in a [`HandlerFn`] type that implements
77/// the [`Handler`] trait.
78///
79/// # Arguments
80///
81/// * `f` - An async function that takes a [`Request`] and returns a [`Future`] resolving to a [`Response`]
82///
83/// # Examples
84///
85/// ```no_run
86/// use micro_http::handler::make_handler;
87/// use http::{Request, Response};
88/// use micro_http::protocol::body::ReqBody;
89/// use std::error::Error;
90///
91/// async fn my_handler(req: Request<ReqBody>) -> Result<Response<String>, Box<dyn Error + Send + Sync>> {
92/// Ok(Response::new("Hello".to_string()))
93/// }
94///
95/// let handler = make_handler(my_handler);
96/// ```
97pub fn make_handler<F, RespBody, Err, Ret>(f: F) -> HandlerFn<F>
98where
99 RespBody: Body,
100 Err: Into<Box<dyn Error + Send + Sync>>,
101 Ret: Future<Output = Result<Response<RespBody>, Err>>,
102 F: Fn(Request<ReqBody>) -> Ret,
103{
104 HandlerFn { f }
105}