pub trait Endpoint: Send + Sync {
// Required method
fn respond(
&mut self,
request: &mut Request,
) -> impl Future<Output = Result<Response>> + Send + Sync;
}Expand description
A trait for types that can handle HTTP requests and generate responses.
Endpoints represent the final destination in the HTTP request processing pipeline. They receive a mutable reference to the request (allowing them to consume the body or modify headers) and return a response or error.
§Implementation Notes
- Endpoints must be
Send + Syncto work in async contexts - The request parameter is mutable, allowing body consumption and header modification
- Implementations should handle errors gracefully and return appropriate HTTP status codes
- Endpoints can be combined with middleware for additional functionality
§Examples
§Simple Text Response
use http_kit::{Request, Response, Result, Endpoint};
struct GreetingEndpoint {
name: String,
}
impl Endpoint for GreetingEndpoint {
async fn respond(&self, _request: &mut Request) -> Result<Response> {
let message = format!("Hello, {}!", self.name);
Ok(Response::new(200, message))
}
}§JSON API Endpoint
use http_kit::{Request, Response, Result, Endpoint};
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct User { name: String, age: u32 }
struct UserEndpoint;
impl Endpoint for UserEndpoint {
async fn respond(&self, request: &mut Request) -> Result<Response> {
match request.method().as_str() {
"GET" => {
let user = User { name: "Alice".into(), age: 30 };
Ok(Response::empty().json(&user)?)
}
"POST" => {
let user: User = request.into_json().await?;
// Process user...
Ok(Response::empty().json(&user)?)
}
_ => Ok(Response::new(405, "Method Not Allowed"))
}
}
}Required Methods§
Sourcefn respond(
&mut self,
request: &mut Request,
) -> impl Future<Output = Result<Response>> + Send + Sync
fn respond( &mut self, request: &mut Request, ) -> impl Future<Output = Result<Response>> + Send + Sync
Processes an HTTP request and generates a response.
This method receives a mutable reference to the request, allowing it to:
- Consume the request body with
take_body()or similar methods - Read headers, URI, method, and other request metadata
- Modify request state if needed (though this is less common)
The method should return either a successful Response or an Error
with an appropriate HTTP status code.
§Arguments
request- Mutable reference to the HTTP request being processed
§Examples
use http_kit::{Request, Response, Result, Endpoint};
struct StatusEndpoint;
impl Endpoint for StatusEndpoint {
async fn respond(&self, request: &mut Request) -> Result<Response> {
let status = format!("Method: {}, URI: {}", request.method(), request.uri());
Ok(Response::new(200, status))
}
}Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.