Expand description
HTTP endpoint abstraction for request handling.
This module provides the core Endpoint trait and supporting types for building
HTTP request handlers. Endpoints represent the final destination for HTTP requests
and are responsible for generating appropriate responses.
§Core Concepts
- Endpoint: A trait for types that can handle HTTP requests and produce responses
- Middleware Integration: Endpoints can be combined with middleware for cross-cutting concerns
- Type Erasure: Support for dynamic dispatch through
AnyEndpoint - Composition: Endpoints can be wrapped and combined in various ways
§Examples
§Basic Endpoint Implementation
use http_kit::{Request, Response, Endpoint, Body};
use core::convert::Infallible;
struct HelloEndpoint;
impl Endpoint for HelloEndpoint {
type Error = Infallible;
async fn respond(&mut self, _request: &mut Request) -> Result<Response, Self::Error> {
Ok(Response::new(Body::from_bytes("Hello, World!")))
}
}§Endpoint with Request Processing
use http_kit::{Request, Response, Endpoint, Body, BoxHttpError};
struct EchoEndpoint;
impl Endpoint for EchoEndpoint {
type Error = BoxHttpError;
async fn respond(&mut self, request: &mut Request) -> Result<Response,Self::Error> {
let body = std::mem::replace(request.body_mut(), Body::empty());
Ok(Response::new(body))
}
}§Using with Middleware
use http_kit::{Request, Response, Endpoint, Middleware, endpoint::WithMiddleware, Body, BoxHttpError};
use http_kit::middleware::MiddlewareError;
struct LoggingMiddleware;
impl Middleware for LoggingMiddleware {
type Error = BoxHttpError;
async fn handle<E: Endpoint>(&mut self, request: &mut Request, mut next: E) -> Result<Response, MiddlewareError<E::Error, Self::Error>> {
println!("Processing request to {}", request.uri());
next.respond(request).await.map_err(MiddlewareError::Endpoint)
}
}
struct MyEndpoint;
impl Endpoint for MyEndpoint {
type Error = BoxHttpError;
async fn respond(&mut self, _request: &mut Request) -> Result<Response,Self::Error> {
Ok(Response::new(Body::from_bytes("OK")))
}
}
let endpoint_with_logging = WithMiddleware::new(MyEndpoint, LoggingMiddleware);Structs§
- AnyEndpoint
- Type-erased endpoint that can hold any endpoint implementation behind a trait object.
- With
Middleware - A wrapper that combines an endpoint with middleware.
Traits§
- Endpoint
- A trait for types that can handle HTTP requests and generate responses.