Examples & Tutorials

Basic HTTP Server

A simple HTTP server with basic routing and response handling.

basic_server.zig
const std = @import("std");
const libxev_http = @import("libxev-http");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    // Create HTTP server
    var server = try libxev_http.createServer(allocator, "127.0.0.1", 8080);
    defer server.deinit();

    // Set up routes
    _ = try server.get("/", indexHandler);
    _ = try server.get("/api/status", statusHandler);
    _ = try server.post("/api/echo", echoHandler);
    _ = try server.get("/users/:id", userHandler);

    std.log.info("Server listening on http://127.0.0.1:8080", .{});
    try server.listen();
}

fn indexHandler(ctx: *libxev_http.Context) !void {
    try ctx.html("<h1>Welcome to libxev-http!</h1><p>High-performance async HTTP framework for Zig</p>");
}

fn statusHandler(ctx: *libxev_http.Context) !void {
    try ctx.json("{\"status\":\"ok\",\"server\":\"libxev-http\",\"version\":\"1.0.0\"}");
}

fn echoHandler(ctx: *libxev_http.Context) !void {
    const body = ctx.getBody() orelse "No body provided";
    try ctx.text(body);
}

fn userHandler(ctx: *libxev_http.Context) !void {
    const user_id = ctx.getParam("id") orelse "unknown";
    const response = try std.fmt.allocPrint(ctx.allocator,
        "{\"user_id\":\"{s}\",\"name\":\"User {s}\"}", .{ user_id, user_id });
    defer ctx.allocator.free(response);
    try ctx.json(response);
}

Features Demonstrated:

  • Basic server creation and setup
  • Route registration for different HTTP methods
  • Parameter extraction from URLs
  • JSON, HTML, and text responses
  • Memory management with allocators
zig build run-basic

Middleware Example

Demonstrates the middleware system with both global and route-specific middleware.

middleware_server.zig
const std = @import("std");
const libxev_http = @import("libxev-http");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    var server = try libxev_http.createServer(allocator, "127.0.0.1", 8080);
    defer server.deinit();

    // Global middleware (applies to all routes)
    try server.use("logging", libxev_http.loggingMiddleware);
    try server.use("request-id", libxev_http.requestIdMiddleware);
    try server.use("cors", libxev_http.corsMiddleware);
    try server.use("security", libxev_http.securityHeadersMiddleware);
    try server.use("custom", customMiddleware);

    // Public routes
    _ = try server.get("/", indexHandler);
    _ = try server.get("/public", publicHandler);

    // Protected route with additional middleware
    const protected_route = try server.get("/api/protected", protectedHandler);
    try protected_route.use("auth", authMiddleware);
    try protected_route.use("rate-limit", rateLimitMiddleware);

    // Admin route with multiple middleware layers
    const admin_route = try server.get("/admin", adminHandler);
    try admin_route.use("auth", authMiddleware);
    try admin_route.use("admin-check", adminCheckMiddleware);

    std.log.info("Server with middleware listening on http://127.0.0.1:8080", .{});
    try server.listen();
}

Features Demonstrated:

  • Global middleware for all routes
  • Route-specific middleware
  • Custom middleware creation
  • Authentication and authorization
  • Request timing and headers
  • Middleware chaining and execution order
zig build run-middleware

Advanced Configuration

Production-ready server with custom configuration, error handling, and security features.

production_server.zig
const std = @import("std");
const libxev_http = @import("libxev-http");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    // Production configuration with strict security
    const config = libxev_http.HttpConfig{
        .connection_timeout_ms = 30000,      // 30 seconds
        .request_timeout_ms = 30000,         // 30 seconds
        .header_timeout_ms = 10000,          // 10 seconds
        .body_timeout_ms = 60000,            // 60 seconds
        .idle_timeout_ms = 5000,             // 5 seconds
        .max_request_size = 1024 * 1024,     // 1MB
        .max_body_size = 10 * 1024 * 1024,   // 10MB
        .enable_request_validation = true,
        .enable_timeout_protection = true,
        .enable_keep_alive = true,
    };

    var server = try libxev_http.createServerWithConfig(
        allocator,
        "0.0.0.0",
        8080,
        config
    );
    defer server.deinit();

    // Production middleware stack
    try server.use("error-handler", errorHandlerMiddleware);
    try server.use("logging", libxev_http.loggingMiddleware);
    try server.use("request-id", libxev_http.requestIdMiddleware);
    try server.use("security", libxev_http.securityHeadersMiddleware);
    try server.use("cors", libxev_http.corsMiddleware);
    try server.use("compression", libxev_http.compressionMiddleware);

    // Health check endpoint
    _ = try server.get("/health", healthHandler);

    // API routes with versioning
    _ = try server.get("/api/v1/status", apiStatusHandler);
    _ = try server.post("/api/v1/upload", uploadHandler);
    _ = try server.get("/api/v1/users/:id", getUserHandler);
    _ = try server.put("/api/v1/users/:id", updateUserHandler);

    // Static file serving
    _ = try server.get("/static/*", staticFileHandler);

    // Catch-all for 404
    _ = try server.get("/*", notFoundHandler);

    std.log.info("Production server listening on http://0.0.0.0:8080", .{});
    try server.listen();
}

Features Demonstrated:

  • Custom production configuration
  • Comprehensive error handling
  • Health check endpoints
  • API versioning
  • File upload handling
  • Static file serving
  • 404 error handling
  • Security middleware stack
zig build run-production

Testing Your Server

Example commands to test your libxev-http server endpoints.

test_commands.sh
#!/bin/bash

# Test basic endpoints
echo "Testing basic endpoints..."

# GET request
curl -X GET http://localhost:8080/

# JSON API endpoint
curl -X GET http://localhost:8080/api/status

# POST with data
curl -X POST http://localhost:8080/api/echo \
  -H "Content-Type: text/plain" \
  -d "Hello, libxev-http!"

# URL parameters
curl -X GET http://localhost:8080/users/123

# Test middleware endpoints
echo -e "\nTesting middleware..."

# Public endpoint
curl -X GET http://localhost:8080/public

# Protected endpoint (should fail)
curl -X GET http://localhost:8080/api/protected

# Protected endpoint with auth
curl -X GET http://localhost:8080/api/protected \
  -H "Authorization: Bearer valid-token"

# Admin endpoint
curl -X GET http://localhost:8080/admin \
  -H "Authorization: Bearer admin-token"

# Test production endpoints
echo -e "\nTesting production endpoints..."

# Health check
curl -X GET http://localhost:8080/health

# API status
curl -X GET http://localhost:8080/api/v1/status

# File upload
curl -X POST http://localhost:8080/api/v1/upload \
  -H "Content-Type: application/octet-stream" \
  -H "Content-Length: 13" \
  -d "test file data"

# User operations
curl -X GET http://localhost:8080/api/v1/users/456

curl -X PUT http://localhost:8080/api/v1/users/456 \
  -H "Content-Type: application/json" \
  -d '{"name":"Updated User","email":"updated@example.com"}'

# Static files
curl -X GET http://localhost:8080/static/css/style.css

# 404 test
curl -X GET http://localhost:8080/nonexistent

echo -e "\nAll tests completed!"

Test Coverage:

  • Basic HTTP methods (GET, POST, PUT)
  • URL parameter extraction
  • Authentication and authorization
  • File upload and static serving
  • Error handling (404, auth failures)
  • Health checks and API status
chmod +x test_commands.sh && ./test_commands.sh