API Reference
Table of Contents
Server Creation & Management
createServer
Creates a new HTTP server with default configuration.
pub fn createServer(allocator: std.mem.Allocator, host: []const u8, port: u16) !*HttpServer
allocator
std.mem.Allocator
Memory allocator for server resources
host
[]const u8
Host address to bind to (e.g., "127.0.0.1")
port
u16
Port number to listen on
createServerWithConfig
Creates a new HTTP server with custom configuration.
pub fn createServerWithConfig(allocator: std.mem.Allocator, host: []const u8, port: u16, config: HttpConfig) !*HttpServer
config
HttpConfig
Custom server configuration
listen
Starts the server and begins accepting connections.
pub fn listen(self: *HttpServer) !void
deinit
Cleans up server resources.
pub fn deinit(self: *HttpServer) void
Routing
get / post / put / delete
Register route handlers for different HTTP methods.
pub fn get(self: *HttpServer, path: []const u8, handler: HandlerFn) !*Route
pub fn post(self: *HttpServer, path: []const u8, handler: HandlerFn) !*Route
pub fn put(self: *HttpServer, path: []const u8, handler: HandlerFn) !*Route
pub fn delete(self: *HttpServer, path: []const u8, handler: HandlerFn) !*Route
path
[]const u8
Route path (supports parameters like "/users/:id" and wildcards "/static/*")
handler
HandlerFn
Function to handle requests: fn(ctx: *Context) anyerror!void
Path Patterns
- Exact paths:
/users
,/api/status
- Parameters:
/users/:id
,/posts/:id/comments/:comment_id
- Wildcards:
/static/*
(matches everything after /static/)
Request Context
Request Information
pub fn getMethod(self: *Context) []const u8
pub fn getPath(self: *Context) []const u8
pub fn getBody(self: *Context) ?[]const u8
pub fn getHeader(self: *Context, name: []const u8) ?[]const u8
pub fn getParam(self: *Context, name: []const u8) ?[]const u8
Response Helpers
pub fn status(self: *Context, code: HttpStatus) void
pub fn json(self: *Context, data: []const u8) !void
pub fn html(self: *Context, content: []const u8) !void
pub fn text(self: *Context, content: []const u8) !void
pub fn setHeader(self: *Context, name: []const u8, value: []const u8) !void
pub fn redirect(self: *Context, location: []const u8, status_code: HttpStatus) !void
HTTP Status Codes
.ok
(200).created
(201).bad_request
(400).unauthorized
(401).not_found
(404).internal_server_error
(500)
Middleware System
use (Global Middleware)
Add middleware that applies to all routes.
pub fn use(self: *HttpServer, name: []const u8, middleware: MiddlewareFn) !void
Route.use (Route-specific Middleware)
Add middleware to a specific route.
pub fn use(self: *Route, name: []const u8, middleware: MiddlewareFn) !void
Built-in Middleware
loggingMiddleware
- Request logging with timingrequestIdMiddleware
- Unique request ID generationcorsMiddleware
- CORS headers supportsecurityHeadersMiddleware
- Security headersbasicAuthMiddleware
- HTTP Basic authenticationrateLimitMiddleware
- Rate limitingerrorHandlerMiddleware
- Error handling
Custom Middleware
Middleware function signature:
fn customMiddleware(ctx: *Context, next: NextFn) anyerror!void {
// Pre-processing
try ctx.setHeader("X-Custom", "value");
// Call next middleware/handler
try next(ctx);
// Post-processing (optional)
}
Configuration
HttpConfig
pub const HttpConfig = struct {
connection_timeout_ms: u32 = 30000,
request_timeout_ms: u32 = 30000,
header_timeout_ms: u32 = 10000,
body_timeout_ms: u32 = 60000,
idle_timeout_ms: u32 = 5000,
max_request_size: usize = 1024 * 1024,
max_body_size: usize = 10 * 1024 * 1024,
enable_request_validation: bool = true,
enable_timeout_protection: bool = true,
enable_keep_alive: bool = true,
};
Preset Configurations
pub fn development() HttpConfig // Relaxed timeouts, detailed logging
pub fn production() HttpConfig // Balanced settings
pub fn testing() HttpConfig // Fast timeouts, small limits
Security & Protection
Timeout Protection
- Connection timeout: Limits total connection lifetime
- Request timeout: Limits time to receive complete request
- Header timeout: Limits time to receive HTTP headers
- Body timeout: Limits time to receive request body
- Idle timeout: Limits connection idle time
Request Validation
- Size limits: Configurable limits for requests, headers, and body
- Format validation: Validates HTTP request format
- Progress monitoring: Monitors request reception progress
Security Configuration Example
const secure_config = HttpConfig{
.connection_timeout_ms = 10000, // 10 seconds
.header_timeout_ms = 3000, // 3 seconds
.body_timeout_ms = 5000, // 5 seconds
.max_request_size = 256 * 1024, // 256KB
.max_body_size = 1024 * 1024, // 1MB
.enable_keep_alive = false, // Disable keep-alive
};
Error Handling
Common Error Types
pub const HttpError = error{
InvalidRequest,
RequestTooLarge,
HeaderTooLarge,
BodyTooLarge,
Timeout,
ConnectionClosed,
OutOfMemory,
};
Error Handler Example
fn errorHandler(ctx: *Context, err: anyerror) !void {
switch (err) {
HttpError.RequestTooLarge => {
ctx.status(.payload_too_large);
try ctx.json("{\"error\":\"Request too large\"}");
},
HttpError.Timeout => {
ctx.status(.request_timeout);
try ctx.json("{\"error\":\"Request timeout\"}");
},
else => {
ctx.status(.internal_server_error);
try ctx.json("{\"error\":\"Internal server error\"}");
},
}
}