#tower-http #hyper-http #web-framework #hyper

hyperlite

Lightweight HTTP framework built on hyper, tokio, and tower

1 unstable release

0.1.0 Oct 29, 2025

#645 in HTTP server

MIT license

70KB
719 lines

Hyperlite

CI Crates.io Documentation License: MIT Status: Beta

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 Service trait 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:

[dependencies]
hyperlite = "0.1"

Or use cargo add:

cargo add hyperlite

Router API

Router API

Creating a Router

#[derive(Clone)]
struct MyState { /* ... */ }

let router = Router::new(MyState { /* ... */ });

Adding Routes

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));

Handler Signature

async fn handler(
	req: Request<BoxBody>,
	state: Arc<YourState>,
) -> Result<Response<Full<Bytes>>, BoxError> {
	// ...
}

Multiple Methods Per Path

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));

Response Builders

Hyperlite provides consistent JSON response helpers following a standard envelope pattern.

Success Responses

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"
	}
}

Error Responses

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"
	}
}

Not Found Responses

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()))
}

Empty Responses

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))
}

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 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
}

With Tower Middleware

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
}

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 std::net::SocketAddr;

let addr: SocketAddr = "127.0.0.1:3000".parse()?;
serve(addr, router).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 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:

  • ✅ 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 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(&params.q, params.limit, params.offset).await?;
    
	Ok(success(StatusCode::OK, results))
}

Example URLs:

  • /search?q=recipe&limit=10
  • /search?q=pasta&limit=20&offset=40

Path Parameters

Extract 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))
}

Request Extensions

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))
}

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 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))
}

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:

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

With State

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

With Middleware

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.

Testing

Hyperlite includes a comprehensive test suite covering all core modules.

Running Tests

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

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 functions
  • router_tests.rs - Router module tests
  • response_tests.rs - Response builder tests
  • extract_tests.rs - Request extractor tests
  • server_tests.rs - Server module tests
  • middleware_tests.rs - Middleware integration tests

Writing Tests

When contributing tests:

  1. Use the helper functions from test_helpers.rs for consistency
  2. Follow the existing test patterns (see examples in each test file)
  3. Use #[tokio::test] for async tests
  4. Use descriptive test names that explain what is being tested
  5. 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 Service that matches paths and dispatches to async handlers.
  • Handlers: Async functions returning hyper::Response types.
  • 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 library
  • cargo test – Run the test suite
  • cargo test -- --nocapture – Run tests with output
  • cargo test <module> – Run a specific test module (for example router_tests)
  • cargo doc --open – Generate and view documentation
  • cargo clippy – Lint the codebase
  • cargo fmt – Format the code
  • cargo 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).

Dependencies

~8–21MB
~247K SLoC