Hyperlite
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.
Overview
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.
Project Status
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.
Features
- ✅ Fast path-based routing via
matchit - ✅ Tower
Servicetrait integration throughout - ✅ Response builders and JSON helpers
- ✅ Server utilities and graceful shutdown
- 🚧 Type-safe request and response helpers
- 🚧 JSON serialization utilities
- 🚧 Middleware composition with Tower layers
- ✅ Request extraction utilities
- ✅ Comprehensive examples and guides
Installation
Add hyperlite to your Cargo.toml:
[]
= "0.1"
Or use cargo add:
Router API
Router API
Creating a Router
let router = new;
Adding Routes
let router = new
.route
.route
.route;
Handler Signature
async
Multiple Methods Per Path
let router = router
.route
.route
.route;
Response Builders
Hyperlite provides consistent JSON response helpers following a standard envelope pattern.
Success Responses
use ;
use ;
use Full;
use Bytes;
use Serialize;
async
Response format:
Error Responses
use ;
use ;
use Full;
use Bytes;
async
Response format:
Not Found Responses
use ;
use ;
use Full;
use Bytes;
async
Empty Responses
use ;
use ;
use Full;
use Bytes;
async
Response Envelope Structure
{
success: boolean,
data?: T,
message?: string,
errors?: ApiError[],
meta: {
timestamp: string,
correlationId?: string
}
}
Server Setup
Hyperlite ships with a serve() helper that boots an HTTP server and shuts it
down gracefully when the process receives Ctrl+C or SIGTERM.
Basic Server
use ;
use Method;
use SocketAddr;
async
With Tower Middleware
use ;
use ServiceBuilder;
use ;
use SocketAddr;
async
Graceful Shutdown
- Ctrl+C: Stops accepting new connections and waits for in-flight requests
- SIGTERM (Unix): Same graceful shutdown path as Ctrl+C
- In-flight requests: Allowed to finish before the server exits
Address Formats
serve() accepts any type convertible into SocketAddr. Parse string addresses before
starting the server:
use SocketAddr;
let addr: SocketAddr = "127.0.0.1:3000".parse?;
serve.await?;
HTTP Protocol Support
- ✅ HTTP/1.1
- 🚧 HTTP/2 (planned for a future release)
The current implementation uses Hyper's HTTP/1 connection builder for maximum compatibility.
Request Extraction
Hyperlite provides type-safe extractors for parsing request data.
JSON Body Parsing
Parse JSON request bodies with automatic validation:
use ;
use Deserialize;
async
Features:
- ✅ Content-Type validation (must be
application/json) - ✅ 1MB size limit (prevents DoS attacks)
- ✅ Descriptive error messages for invalid JSON
- ✅ Works with any serde-deserializable type
Query Parameters
Parse URL query strings into typed structs:
use ;
use Deserialize;
async
Example URLs:
/search?q=recipe&limit=10/search?q=pasta&limit=20&offset=40
Path Parameters
Extract dynamic segments from URL paths:
use ;
use Uuid;
// Route: /users/{id}/posts/{post_id}
async
// Register route with path parameters
let router = new
.route;
Alternative: Get all params as HashMap:
use path_params;
use HashMap;
async
Request Extensions
Extract typed data stored in request extensions (e.g., by middleware):
use ;
use Uuid;
// Auth middleware inserts user_id into extensions
async
Error Handling
All extractors return Result<T, BoxError> with descriptive error messages:
- JSON parsing: "Invalid JSON: expected value at line 1 column 5"
- Query params: "Invalid query parameters: missing field
q" - Path params: "Path parameter 'id' not found"
- Extensions: "Extension of type uuid::Uuid not found"
Convert errors to HTTP responses in your handlers:
async
Examples
Hyperlite ships with three progressively richer examples. Build and run them directly from the workspace root.
Hello World
Minimal server with a single route and JSON response envelope:
Demonstrates basic routing, handler signatures, response builders, and graceful shutdown. Test with:
With State
Stateful routing that exercises every request extractor and shared application context:
Learn how to parse JSON bodies, query strings, and path parameters while mutating shared state safely. Useful curl helpers:
# Get service stats
# Create a new user
# List users with pagination
# Fetch a specific user
With Middleware
Production-style stack layering request IDs, tracing, CORS, and custom middleware:
RUST_LOG=info
Highlights Tower's ServiceBuilder, middleware ordering, and request ID
propagation. Try the following:
# Health check with aggregated request stats
# Observe propagated request IDs
# Echo JSON payloads (CORS-enabled)
# Execute a CORS preflight request
All examples support Ctrl+C for graceful shutdown. Consult the source files in
examples/ for extensive inline commentary.
Testing
Hyperlite includes a comprehensive test suite covering all core modules.
Running Tests
Run all tests:
Run tests for a specific module:
Run with output:
Run ignored tests (integration tests that bind to ports):
Test Coverage
The test suite covers:
- ✅ Router: Route registration, path matching, method filtering, 404/405 handling, path parameters
- ✅ Response Builders: Envelope structure, JSON serialization, correlation IDs, error responses
- ✅ Extractors: JSON body parsing, query parameters, path parameters, extensions
- ✅ Server: ConnectionHandler body conversion (limited serve() testing)
- ✅ Middleware: Tower layer composition, CORS, request-id, custom middleware
Test Organization
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 tests
Writing Tests
When contributing tests:
- Use the helper functions from
test_helpers.rsfor consistency - Follow the existing test patterns (see examples in each test file)
- Use
#[tokio::test]for async tests - Use descriptive test names that explain what is being tested
- Add comments explaining complex test scenarios
Coverage Goals
The test suite aims for 80%+ code coverage on core functionality:
- Router: 90%+ (critical path)
- Response builders: 85%+
- Extractors: 85%+
- Server: 60%+ (limited due to signal handling complexity)
- Overall: 80%+
Architecture
- Router: Tower
Servicethat matches paths and dispatches to async handlers. - Handlers: Async functions returning
hyper::Responsetypes. - Middleware: Standard Tower layers for cross-cutting concerns.
- Server: Hyper server with graceful shutdown hooks and connection limits.
Comparison
- vs Axum: More control, no macros, fewer implicit behaviors—but less ergonomic extractors.
- vs Actix-web: Simpler Tower-based stack—trades away built-in actor features.
- vs Warp: More explicit and debuggable—at the expense of more boilerplate.
- vs raw Hyper: Adds routing and middleware composition while staying close to primitives.
Development
cargo build– Build the librarycargo test– Run the test suitecargo test -- --nocapture– Run tests with outputcargo test <module>– Run a specific test module (for examplerouter_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 binaries
Roadmap
- Phase 1: ✅ Project setup and dependency scaffolding
- Phase 2: ✅ Core router implementation
- Phase 3: ✅ Response builders
- Phase 4: ✅ Server utilities
- Phase 5: ✅ Request extractors
- Phase 6: ✅ Documentation and examples
License
Hyperlite is licensed under the MIT License. See LICENSE for details.
Contributing
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).