Something went wrong. Try again.
An HTTP library for Zig 0.17, server and client, HTTP/1.0 through HTTP/3, with the protocol in a module that owns no socket.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the server calls for each request.//!//! One function, taking the request and the response, and version-independent//! by construction: there is nothing in `Request` or `Response` that is//! particular to one version, so the same handler serves HTTP/1.0, HTTP/1.1//! and HTTP/2 without being recompiled against a different interface.//!//! ## A handler must be reentrant//!//! This is the one thing HTTP/2 asks of a handler that HTTP/1.1 did not, and//! it is easy to miss because the type did not change.//!//! Under HTTP/1.1 a connection carries one request at a time, so a handler's//! `context` was touched by one task per connection. HTTP/2 multiplexes: up//! to `http2.Config.max_concurrent_streams` requests can be inside the same//! handler, on the same connection, at the same moment. Any state reached//! through `context` is therefore shared across tasks and needs whatever//! discipline that implies — an atomic, a mutex, or no mutation at all.//!//! The `Counter` in this file's own `init` test is the shape of the trap: a//! plain `self.seen += 1` is a data race the moment HTTP/2 is enabled, and//! `src/main.zig` uses `std.atomic.Value` for exactly that reason.//!//! A handler may return an error. That is not the way to send a `404` — that//! is `res.status = .not_found` — it is for the case where the handler cannot//! continue at all, and what the server does about it depends on how far the//! response had got: if nothing has been written, a `500` goes out in its//! place; if the head is already on the wire, the only honest thing left is//! to close the connection, so that the client sees a truncated response//! rather than a complete-looking one that is missing half its body.
const std = @import("std");
const Request = @import("Request.zig");const Response = @import("Response.zig");
const Handler = @This();
context: ?*anyopaque,serveFn: *const fn (context: ?*anyopaque, req: *Request, res: *Response) Error!void,
/// `anyerror`, because a handler's failures are its own business and a/// closed set here would mean every application error had to be flattened/// into one the library had thought of. The server does not inspect the/// error; it reports it and decides whether the connection can survive.pub const Error = anyerror;
/// Calls the wrapped function with its context.////// This is what a driver does once per request. A handler's own code calls it/// only to hand a request on to another handler — a router choosing one by/// path, say — and whatever that one returns comes straight back.pub fn serve(h: Handler, req: *Request, res: *Response) Error!void { return h.serveFn(h.context, req, res);}
test serve { const Refuse = struct { fn serve(req: *Request, res: *Response) Error!void { _ = .{ req, res }; return error.NotToday; } }; const handler: Handler = .initStateless(Refuse.serve); // The error is the handler's own, and is passed through untouched. try std.testing.expectError(error.NotToday, handler.serve(undefined, undefined));}
/// Wraps a function and the pointer it wants as its first argument, with the/// cast to and from `*anyopaque` generated rather than written out.////// var app: App = .{ .root = dir };/// const handler: Handler = .init(&app, App.serve);pub fn init( context: anytype, comptime serveFn: fn (@TypeOf(context), *Request, *Response) Error!void,) Handler { const Context = @TypeOf(context); comptime std.debug.assert(@typeInfo(Context) == .pointer); const shim = struct { fn serve(untyped: ?*anyopaque, req: *Request, res: *Response) Error!void { return serveFn(@ptrCast(@alignCast(untyped.?)), req, res); } }; return .{ .context = @constCast(context), .serveFn = shim.serve };}
test init { const Counter = struct { seen: usize = 0, fn serve(self: *@This(), req: *Request, res: *Response) Error!void { _ = .{ req, res }; self.seen += 1; } }; var counter: Counter = .{}; const handler: Handler = .init(&counter, Counter.serve); try handler.serve(undefined, undefined); try std.testing.expectEqual(@as(usize, 1), counter.seen);}
/// Wraps a function that needs no state of its own.pub fn initStateless(comptime serveFn: fn (*Request, *Response) Error!void) Handler { const shim = struct { fn serve(untyped: ?*anyopaque, req: *Request, res: *Response) Error!void { _ = untyped; return serveFn(req, res); } }; return .{ .context = null, .serveFn = shim.serve };}
test initStateless { const Hello = struct { fn serve(req: *Request, res: *Response) Error!void { _ = req; try res.send("hello"); } }; const handler: Handler = .initStateless(Hello.serve); // There is no state, so there is no context to point at. try std.testing.expect(handler.context == null);}