http
Implementation of the RFC 2616/7230-7235 and 6455 specifications for HTTP 1.1 and Websocket protocols in Rust
Repository Information
| Language | Rust |
|---|---|
| Stars | 7 |
| Forks | 0 |
| Last Updated | 5/31/2026 |
HTTP & WebSockets in Rust
A production-ready implementation of HTTP 1.1 and WebSocket protocols built from
scratch in Rust using idiomatic Rust practices and the tokio async runtime.
✨ Recently Enhanced: This implementation now includes HTTP/1.1 persistent connections (keep-alive), chunked transfer encoding, WebSocket frame buffering, server-initiated ping/pong health checks, and comprehensive structured logging. See REFINEMENTS.md for details.
Table of Contents
- Features
- Architecture
- Usage
- Example Usage
- Code Examples
- Dependencies
- Security Features
- Performance Characteristics
- Testing
- Future Improvements
- License
Features
HTTP 1.1 Support (RFC 2616/7230-7235)
- ✅ HTTP request parsing (GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, TRACE, CONNECT)
- ✅ Persistent connections (Keep-Alive) - multiple requests per TCP connection
- ✅ Chunked transfer encoding - for streaming responses
- ✅ Content-Length body reading - proper request body handling
- ✅ HTTP response generation with proper status codes
- ✅ Auto-generated standard headers (Date, Server, Connection, Keep-Alive)
- ✅ Static file serving with proper Content-Type detection
- ✅ Request header parsing and response header setting
- ✅ Directory traversal protection
- ✅ Support for multiple content types (HTML, CSS, JS, JSON, images, etc.)
- ✅ Header size protection (16KB limit to prevent header bombs)
WebSocket Support (RFC 6455)
- ✅ WebSocket handshake (Sec-WebSocket-Key verification)
- ✅ Full frame buffering - handles frames larger than buffer size
- ✅ Server-initiated PING/PONG - health checks every 30s with timeout detection
- ✅ Protocol validation - enforces masking, frame size limits, close codes
- ✅ WebSocket frame parsing and generation
- ✅ Text and binary message support
- ✅ Ping/Pong frame handling with automatic responses
- ✅ Close frame with status codes and reasons
- ✅ Connection close handling
- ✅ Echo server functionality for testing
- ✅ Control frame validation (125 byte max payload)
Type Safety & Good Practices
- ✅ Strongly-typed HTTP methods (
HttpMethodenum) - ✅ Strongly-typed HTTP status codes (
HttpStatusCodeenum) - ✅ Comprehensive error handling with
thiserror - ✅ Builder pattern for HTTP responses
- ✅ Structured logging with
tracing- production-ready observability - ✅ Async/await throughout - non-blocking I/O with Tokio
- ✅ Extensive test coverage (17 tests, all passing)
- ✅ Zero clippy warnings - clean, idiomatic Rust code
Architecture
1src/2├── main.rs # Server entry point3├── lib.rs # Library exports4├── config.rs # Configuration5├── error.rs # Error types6├── protocol/ # HTTP implementation7│ ├── mod.rs # HTTP connection handling8│ ├── request.rs # HTTP request parsing9│ ├── response.rs # HTTP response generation10│ └── handler.rs # HTTP request handlers11└── websocket/ # WebSocket implementation12 ├── mod.rs # WebSocket connection handling13 ├── handshake.rs # WebSocket handshake14 └── frame.rs # WebSocket frame parsing/generationUsage
Running the Server
1cargo runThe server will start on http://127.0.0.1:8080 by default.
Enable detailed logging:
1RUST_LOG=http=debug cargo runLog levels available: error, warn, info, debug, trace
Testing
1cargo testRun with clippy for additional checks:
1cargo clippy --all-targetsHTTP Endpoints
GET /- Servesstatic/index.htmlGET /path/to/file- Serves static files from thestatic/directoryPOST /any/path- Echo endpoint that returns the request body as JSON
WebSocket
Connect to ws://127.0.0.1:8080 to establish a WebSocket connection. The server
will:
- Echo back any text messages prefixed with "Echo: "
- Echo back binary messages as-is
- Respond to ping frames with pong frames
- Handle connection close properly
Example Usage
HTTP Client
1# Get the index page2curl http://127.0.0.1:8080/34# Post some data5curl -X POST http://127.0.0.1:8080/api/test -d "Hello, Server!"WebSocket Client (Browser)
1const socket = new WebSocket("ws://127.0.0.1:8080");2socket.onopen = () => {3 console.log("Connected");4 socket.send("Hello, Rust!");5};6socket.onmessage = (e) => console.log("Received:", e.data);7socket.onerror = (e) => console.error("WebSocket error:", e);8socket.onclose = (e) => console.log("Connection closed:", e.code, e.reason);Code Examples
Creating HTTP Responses
1use http::http::{HttpResponse, HttpStatusCode};23// Simple text response4let response = HttpResponse::ok()5 .with_text("Hello, World!");67// JSON response8let response = HttpResponse::new(HttpStatusCode::Created)9 .with_json(r#"{"message": "Resource created"}"#);1011// Custom headers12let response = HttpResponse::ok()13 .with_header("cache-control", "no-cache")14 .with_html("<h1>Hello</h1>");WebSocket Frame Handling
1use http::websocket::WebSocketFrame;23// Create frames4let text_frame = WebSocketFrame::Text("Hello".to_string());5let ping_frame = WebSocketFrame::Ping(b"ping data".to_vec());6let close_frame = WebSocketFrame::Close;78// Serialize to bytes9let bytes = text_frame.to_bytes();1011// Parse from bytes12if let Some(frame) = WebSocketFrame::parse(&bytes) {13 match frame {14 WebSocketFrame::Text(text) => println ! ("Received: {}", text),15 WebSocketFrame::Close => println! ("Connection closing"),16 _ => {}17 }18}Dependencies
| Dependency | Purpose |
|---|---|
tokio |
Async runtime with full features |
bytes |
Byte manipulation utilities |
base64 |
Base64 encoding for WebSocket handshake |
sha1 |
SHA1 hashing for WebSocket handshake |
thiserror |
Error handling macros |
Security Features
- Directory traversal protection (prevents access outside static directory)
- Proper path canonicalization
- Input validation for HTTP requests
- WebSocket handshake validation
Performance Characteristics
- Asynchronous I/O using
tokio - Connection pooling through
tokio::spawn - Zero-copy buffer management where possible
- Efficient WebSocket frame parsing
Testing
The project includes comprehensive tests:
- HTTP request/response parsing
- WebSocket handshake validation
- WebSocket frame serialization/deserialization
- HTTP method and status code handling
- Integration tests for both protocols
Future Improvements
- HTTP/2 support
- TLS/SSL support
- WebSocket extensions (compression, etc.)
- WebSocket message fragmentation - reassembly of fragmented messages
- Request routing and middleware
- Connection pooling and rate limiting
-
Logging and metrics✅ Implemented withtracing - Configuration file support
-
HTTP/1.1 Keep-Alive✅ Implemented -
Chunked transfer encoding✅ Implemented
License
This project is licensed under the MIT License - see the LICENSE file for details.
Want to see more? Visit my GitHub page for all my repositories and contributions.
View All Repositories on GitHub →