Skip to content

Commit

Permalink
docs(web): add detailed documentation for request handler types and t…
Browse files Browse the repository at this point in the history
…raits
  • Loading branch information
zavakid committed Dec 12, 2024
1 parent 78c6133 commit d8ecdde
Showing 1 changed file with 30 additions and 3 deletions.
33 changes: 30 additions & 3 deletions crates/web/src/handler.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
//! Request handler types and traits for the web framework.
//!
//! This module provides the core abstractions for handling HTTP requests:
//! - `RequestHandler` trait for implementing request handlers
//! - `FnHandler` for wrapping async functions as handlers
//! - Helper functions for creating handlers
use crate::body::ResponseBody;
use crate::fn_trait::FnTrait;

Expand All @@ -9,6 +16,10 @@ use http::Response;
use crate::extract::FromRequest;
use std::marker::PhantomData;

/// Trait for types that can handle HTTP requests.
///
/// Implementors must provide an `invoke` method that processes the request
/// and returns a response. This is the core trait for request handling.
#[async_trait]
pub trait RequestHandler: Send + Sync {
async fn invoke<'server, 'req>(
Expand Down Expand Up @@ -54,7 +65,14 @@ impl RequestHandler for &dyn RequestHandler {
}
}

/// a `FnTrait` holder which represents any async Fn
/// A wrapper type that converts async functions into request handlers.
///
/// This allows regular async functions to be used as request handlers
/// by implementing the `RequestHandler` trait for them.
///
/// Type parameters:
/// - `F`: The async function type
/// - `Args`: The function arguments type
pub struct FnHandler<F, Args> {
f: F,
_phantom: PhantomData<fn(Args)>,
Expand All @@ -69,6 +87,9 @@ where
}
}

/// Creates a new `FnHandler` that wraps the given async function.
///
/// This is the main way to convert an async function into a request handler.
pub fn handler_fn<F, Args>(f: F) -> FnHandler<F, Args>
where
F: FnTrait<Args>,
Expand All @@ -79,9 +100,15 @@ where
#[async_trait]
impl<F, Args> RequestHandler for FnHandler<F, Args>
where
F: for<'r> FnTrait<Args::Output<'r>>,
for<'r> <F as FnTrait<Args::Output<'r>>>::Output: Responder,
// Args must implement [`FromRequest`] trait
// This allows extracting the function arguments from the HTTP request
Args: FromRequest,
// F must be a function [`FnTrait`] that can accept Args::Output<'r> for any lifetime 'r
// This allows the function to work with arguments that have different lifetimes
for<'r> F: FnTrait<Args::Output<'r>>,
// The output of calling F must implement [`Responder`] trait
// This ensures the function's return value can be converted into an HTTP response
for<'r> <F as FnTrait<Args::Output<'r>>>::Output: Responder,
{
async fn invoke<'server, 'req>(
&self,
Expand Down

0 comments on commit d8ecdde

Please sign in to comment.