| Crates.io | hyperlite |
| lib.rs | hyperlite |
| version | 0.1.0 |
| created_at | 2025-10-29 19:16:04.422226+00 |
| updated_at | 2025-10-29 19:16:04.422226+00 |
| description | Lightweight HTTP framework built on hyper, tokio, and tower |
| homepage | https://github.com/kriyaetive/hyperlite |
| repository | https://github.com/kriyaetive/hyperlite |
| max_upload_size | |
| id | 1907219 |
| size | 211,324 |
A lightweight, fast HTTP framework built on hyper, tokio, and tower.
Beta notice: Hyperlite is still undergoing hardening. Expect breaking surface changes and perform a full security review before shipping production traffic through it.
Hyperlite keeps you close to the metal while smoothing over the rough edges of building HTTP services with hyper. It targets teams that need full control of the HTTP layer without vendor lock-in or the churn that comes with higher-level frameworks. Hyperlite composes cleanly with the Tower ecosystem, making it straightforward to layer in middleware such as tracing, CORS, authentication, and rate limiting. Bring your own data structures, serialization, and error handling—Hyperlite stays out of the way.
Hyperlite is currently in beta. The API may change without notice as we gather feedback from early adopters, and the framework has not been through comprehensive production security reviews. Deploy behind proven edge infrastructure (TLS termination, WAF, rate limiting) and add defense-in-depth middleware before relying on it for sensitive workloads.
matchitService trait integration throughoutAdd hyperlite to your Cargo.toml:
[dependencies]
hyperlite = "0.1"
Or use cargo add:
cargo add hyperlite
#[derive(Clone)]
struct MyState { /* ... */ }
let router = Router::new(MyState { /* ... */ });
let router = Router::new(state)
.route("/users", Method::GET, Arc::new(list_users))
.route("/users", Method::POST, Arc::new(create_user))
.route("/users/{id}", Method::GET, Arc::new(get_user));
async fn handler(
req: Request<BoxBody>,
state: Arc<YourState>,
) -> Result<Response<Full<Bytes>>, BoxError> {
// ...
}
let router = router
.route("/api/resource", Method::GET, Arc::new(get_handler))
.route("/api/resource", Method::POST, Arc::new(post_handler))
.route("/api/resource", Method::PUT, Arc::new(put_handler));
Hyperlite provides consistent JSON response helpers following a standard envelope pattern.
use hyperlite::{success, BoxError};
use hyper::{Response, StatusCode};
use http_body_util::Full;
use bytes::Bytes;
use serde::Serialize;
#[derive(Serialize)]
struct User {
id: u64,
name: String,
}
async fn get_user() -> Result<Response<Full<Bytes>>, BoxError> {
let user = User { id: 1, name: "Alice".to_string() };
Ok(success(StatusCode::OK, user))
}
Response format:
{
"success": true,
"data": { "id": 1, "name": "Alice" },
"meta": {
"timestamp": "2024-01-15T10:30:00Z"
}
}
use hyperlite::{failure, ApiError, BoxError};
use hyper::{Response, StatusCode};
use http_body_util::Full;
use bytes::Bytes;
async fn validate_input() -> Result<Response<Full<Bytes>>, BoxError> {
let errors = vec![
ApiError::new("VALIDATION_ERROR", "Email is required"),
ApiError::new("VALIDATION_ERROR", "Password too short"),
];
Ok(failure(StatusCode::BAD_REQUEST, errors))
}
Response format:
{
"success": false,
"errors": [
{ "code": "VALIDATION_ERROR", "message": "Email is required" },
{ "code": "VALIDATION_ERROR", "message": "Password too short" }
],
"meta": {
"timestamp": "2024-01-15T10:30:00Z"
}
}
use hyperlite::{not_found, BoxError};
use hyper::{Response, StatusCode};
use http_body_util::Full;
use bytes::Bytes;
async fn get_resource() -> Result<Response<Full<Bytes>>, BoxError> {
Ok(not_found("/api/users/999".to_string()))
}
use hyperlite::{empty, BoxError};
use hyper::{Response, StatusCode};
use http_body_util::Full;
use bytes::Bytes;
async fn delete_resource() -> Result<Response<Full<Bytes>>, BoxError> {
// delete logic here
Ok(empty(StatusCode::NO_CONTENT))
}
{
success: boolean,
data?: T,
message?: string,
errors?: ApiError[],
meta: {
timestamp: string,
correlationId?: string
}
}
Hyperlite ships with a serve() helper that boots an HTTP server and shuts it
down gracefully when the process receives Ctrl+C or SIGTERM.
use hyperlite::{Router, serve};
use hyper::Method;
use std::net::SocketAddr;
#[tokio::main]
async fn main() -> Result<(), hyperlite::BoxError> {
let router = Router::new(state)
.route("/hello", Method::GET, hello_handler);
let addr: SocketAddr = "127.0.0.1:3000".parse().expect("invalid address");
serve(addr, router).await
}
use hyperlite::{Router, serve};
use tower::ServiceBuilder;
use tower_http::{
cors::CorsLayer,
trace::TraceLayer,
};
use std::net::SocketAddr;
#[tokio::main]
async fn main() -> Result<(), hyperlite::BoxError> {
let service = ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(CorsLayer::permissive())
.service(
Router::new(state)
.route("/api/users", Method::GET, list_users)
);
let addr: SocketAddr = "0.0.0.0:8080".parse().expect("invalid address");
serve(addr, service).await
}
serve() accepts any type convertible into SocketAddr. Parse string addresses before
starting the server:
use std::net::SocketAddr;
let addr: SocketAddr = "127.0.0.1:3000".parse()?;
serve(addr, router).await?;
The current implementation uses Hyper's HTTP/1 connection builder for maximum compatibility.
Hyperlite provides type-safe extractors for parsing request data.
Parse JSON request bodies with automatic validation:
use hyperlite::{parse_json_body, success};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
email: String,
username: String,
password: String,
}
async fn register(
req: Request<BoxBody>,
state: Arc<AppState>,
) -> Result<Response<Full<Bytes>>, BoxError> {
let payload = parse_json_body::<CreateUser>(req).await?;
// Validate and create user
// payload.email, payload.username, payload.password
Ok(success(StatusCode::CREATED, user))
}
Features:
application/json)Parse URL query strings into typed structs:
use hyperlite::{query_params, success};
use serde::Deserialize;
#[derive(Deserialize)]
struct SearchParams {
q: String,
#[serde(default)]
limit: Option<i64>,
#[serde(default)]
offset: Option<i64>,
}
async fn search(
req: Request<BoxBody>,
state: Arc<AppState>,
) -> Result<Response<Full<Bytes>>, BoxError> {
let params = query_params::<SearchParams>(&req)?;
// Use params.q, params.limit, params.offset
let results = search_database(¶ms.q, params.limit, params.offset).await?;
Ok(success(StatusCode::OK, results))
}
Example URLs:
/search?q=recipe&limit=10/search?q=pasta&limit=20&offset=40Extract dynamic segments from URL paths:
use hyperlite::{path_param, success};
use uuid::Uuid;
// Route: /users/{id}/posts/{post_id}
async fn get_post(
req: Request<BoxBody>,
state: Arc<AppState>,
) -> Result<Response<Full<Bytes>>, BoxError> {
// Extract and parse path parameters
let user_id: Uuid = path_param(&req, "id")?;
let post_id: Uuid = path_param(&req, "post_id")?;
let post = fetch_post(user_id, post_id).await?;
Ok(success(StatusCode::OK, post))
}
// Register route with path parameters
let router = Router::new(state)
.route("/users/{id}/posts/{post_id}", Method::GET, Arc::new(|req, state| {
Box::pin(get_post(req, state))
}));
Alternative: Get all params as HashMap:
use hyperlite::path_params;
use std::collections::HashMap;
async fn handler(req: Request<BoxBody>) -> Result<Response<Full<Bytes>>, BoxError> {
let params: HashMap<String, String> = path_params(&req)?;
let id = params.get("id").ok_or("Missing id")?;
Ok(success(StatusCode::OK, data))
}
Extract typed data stored in request extensions (e.g., by middleware):
use hyperlite::{get_extension, success};
use uuid::Uuid;
// Auth middleware inserts user_id into extensions
async fn protected_handler(
req: Request<BoxBody>,
state: Arc<AppState>,
) -> Result<Response<Full<Bytes>>, BoxError> {
// Extract user ID inserted by auth middleware
let user_id = get_extension::<Uuid>(&req)?;
let user_data = fetch_user_data(user_id).await?;
Ok(success(StatusCode::OK, user_data))
}
All extractors return Result<T, BoxError> with descriptive error messages:
q"Convert errors to HTTP responses in your handlers:
async fn handler(req: Request<BoxBody>) -> Result<Response<Full<Bytes>>, BoxError> {
let payload = parse_json_body::<CreateUser>(req).await
.map_err(|err| {
// Log error and return user-friendly message
tracing::error!("JSON parse error: {}", err);
BoxError::from("Invalid request body")
})?;
Ok(success(StatusCode::OK, payload))
}
Hyperlite ships with three progressively richer examples. Build and run them directly from the workspace root.
Minimal server with a single route and JSON response envelope:
cargo run --example hello_world
Demonstrates basic routing, handler signatures, response builders, and graceful shutdown. Test with:
curl http://127.0.0.1:3000/hello
Stateful routing that exercises every request extractor and shared application context:
cargo run --example with_state
Learn how to parse JSON bodies, query strings, and path parameters while mutating shared state safely. Useful curl helpers:
# Get service stats
curl http://127.0.0.1:3000/stats
# Create a new user
curl -X POST http://127.0.0.1:3000/users \
-H "Content-Type: application/json" \
-d '{"name":"Alice","email":"alice@example.com"}'
# List users with pagination
curl "http://127.0.0.1:3000/users?limit=10&offset=0"
# Fetch a specific user
curl http://127.0.0.1:3000/users/6f9619ff-8b86-d011-b42d-00cf4fc964ff
Production-style stack layering request IDs, tracing, CORS, and custom middleware:
RUST_LOG=info cargo run --example with_middleware
Highlights Tower's ServiceBuilder, middleware ordering, and request ID
propagation. Try the following:
# Health check with aggregated request stats
curl http://127.0.0.1:3000/health
# Observe propagated request IDs
curl -v http://127.0.0.1:3000/protected
# Echo JSON payloads (CORS-enabled)
curl -X POST http://127.0.0.1:3000/echo \
-H "Content-Type: application/json" \
-d '{"test":"data"}'
# Execute a CORS preflight request
curl -X OPTIONS http://127.0.0.1:3000/echo \
-H "Origin: http://localhost:3001" \
-H "Access-Control-Request-Method: POST"
All examples support Ctrl+C for graceful shutdown. Consult the source files in
examples/ for extensive inline commentary.
Hyperlite includes a comprehensive test suite covering all core modules.
Run all tests:
cargo test
Run tests for a specific module:
cargo test router_tests
cargo test response_tests
cargo test extract_tests
cargo test middleware_tests
Run with output:
cargo test -- --nocapture
Run ignored tests (integration tests that bind to ports):
cargo test -- --ignored
The test suite covers:
Tests are organized in the tests/ directory:
test_helpers.rs - Shared test utilities and helper functionsrouter_tests.rs - Router module testsresponse_tests.rs - Response builder testsextract_tests.rs - Request extractor testsserver_tests.rs - Server module testsmiddleware_tests.rs - Middleware integration testsWhen contributing tests:
test_helpers.rs for consistency#[tokio::test] for async testsThe test suite aims for 80%+ code coverage on core functionality:
Service that matches paths and dispatches to async handlers.hyper::Response types.cargo build – Build the librarycargo test – Run the test suitecargo test -- --nocapture – Run tests with outputcargo test <module> – Run a specific test module (for example router_tests)cargo doc --open – Generate and view documentationcargo clippy – Lint the codebasecargo fmt – Format the codecargo run --example <name> – Run a specific example (hello_world, with_state, with_middleware)cargo build --examples – Build all example binariesHyperlite is licensed under the MIT License. See LICENSE for details.
Contributions are welcome! Please read our Contributing Guidelines before submitting a pull request.
By contributing, you agree to abide by our Code of Conduct (included in CONTRIBUTING.md).