HTTP/1.1 routing, middleware, streaming, WebSocket, SSE, static files, and an integrated asynchronous I/O runtime.
With Zig 0.14.1, add mox to your project:
zig fetch --save=mox git+https://github.com/lovez-dev/mox.git#mainIn build.zig, attach the module to your executable:
const dep = b.dependency("mox", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("mox", dep.module("mox"));const std = @import("std");
const mox = @import("mox");
fn hello(_: *mox.server.Context) !mox.response.Response {
return .{ .body = "hello\n" };
}
pub fn main() !void {
try mox.server.serve(.{
.gpa = std.heap.page_allocator,
.address = mox.io.Address.loopback(8080),
.routes = &.{.{ .method = .GET, .path = "/", .handler = hello }},
});
}Use the feature namespaces for related APIs: mox.server, mox.router, mox.response,
mox.middleware, mox.template, mox.multipart, mox.websocket, mox.sse, and
mox.observability. mox.io is the asynchronous I/O runtime and mox.http is the low-level
HTTP codec.
For blocking handlers, enable mox.server.Config.blocking_handlers and set
max_inflight_requests to bound admitted work. mox.server.Config.executor defaults to two
workers; standalone I/O loops create none unless requested. WebSocket message callbacks can
opt into workers with mox.response.Response.upgradeBlocking.
Metrics are opt-in. Initialize var collector: mox.observability.Collector = .{}; and set
Config.metrics = &collector. Read an owned snapshot with
mox.observability.getMetrics(&collector) or register mox.observability.metricsHandler as a
route. Keep the collector at a stable address until all borrowing servers stop. Sharing it
aggregates their counters; snapshot fields are atomic reads, not a transaction. Without a
collector, lifecycle callbacks still run with request ID zero and the metrics route returns
503.
Pass caller-owned mox.middleware.RateLimitState and mox.middleware.RequestIds instances
through Config.rate_limit_state and Config.request_ids. Initialize each with .{} and
keep its address stable until every borrowing server stops. Sharing an instance shares its
counters. Missing state returns 503 before the wrapped handler runs.
mox.middleware.logging and jsonLog write JSON Lines to stdout with UTC ISO 8601 time,
level, event, msg, method, route template, status, duration, and an optional response
request ID. Raw paths, path parameter values, queries, request headers, and bodies are
omitted. Unmatched requests use (unmatched). Handler errors propagate to the error boundary;
wrap requestId with logging to include generated request IDs. Configure either this
middleware or the completion log callback to avoid duplicate access records.
Diagnostics are disabled by default. Set Config.on_diagnostic to
mox.observability.jsonDiagnosticLog or a custom callback to receive runtime failures.
Diagnostic JSON uses the same stdout format and includes error.code and error.message.
CORS denies cross-origin access by default. Pass explicit CorsOptions.allow_origins when
using mox.middleware.cors. A single "*" permits public access without credentials;
allow_credentials = true requires explicit origins and rejects wildcard configuration.
The default handler error response is JSON with status 500 and code internal_server_error.
To record the original error name, set Config.on_request_complete to
mox.observability.jsonAccessLog or provide your own callback. For chunked requests, an
exceeded body limit returns 413; a body allocation failure returns 503 if the server has
enough resources to write the response, otherwise it closes the connection.
Low-level callers of mox.http.decodeChunked or ChunkedDecoder.decode must handle
error.OutOfMemory separately from the .body_too_large parse result.
A parsed chunked request reports body_complete = false until its body is decoded.
Use Config.application_state to pass application-owned state into
Context.application_state. Keep it valid until the server stops and synchronize access from
worker callbacks. The board example keeps its application instance local to main.
Run the basic server with zig build run. Import asynchronous I/O from mox.io; use
dep.module("mox_io") only in build.zig to attach the dependency module.
mox.io.Dispatcher forwards completions to bound adapters. Group.all and Group.race
compose operations without hand-written completion matching. See the
TCP example.
The runtime uses native socket and completion APIs instead of a separate networking library. The HTTP/1.1 codec runs on the same loop, so request framing, I/O cancellation, and buffer retirement share one lifecycle. Deploy behind a TLS-terminating proxy for HTTPS.
The I/O source tree follows five responsibilities:
src/mox_io/
mox_io.zig Public facade; exported names remain stable.
error.zig Shared failures and diagnostic values.
fmt.zig Formatting into caller-owned storage.
testing.zig Test-only injection and fixtures.
api/ Sockets, files, streams, groups, processes, and their adapters.
core/ Loop, driver contract, lifecycle state, and portable value types.
mem/ Allocation, tracking, arenas, and byte operations.
native/ Backend selection, system profiles, ABI conversion, and OS code.
runtime/ Blocking Executor, per-Loop ExecutorLease, and owner threads.
Native code consumes portable contracts from core/; it does not import api/ adapters.
Platform helper selection stays in native/system.zig. The optional standalone entry,
panic hooks, and compiler memory routines live in native/startup.zig; the public
runtime namespace keeps exposing those helpers.
Loop owns operation identities, deadlines, cancellation reasons, partial-transfer progress,
and resource retirement. Native close retries retain the resource until release is proven;
a hidden descriptor from a failed open follows the same close policy before its terminal
result becomes visible. Drivers report native retirement and preserve results across control
errors. A cancellation request alone does not release borrowed buffers.
Executor retains blocking jobs until their Loop client consumes the result; its per-Loop
ExecutorLease reserves and drains that client lease. Runtime manages independent owner Loops and
threads. Runtime admission and each Inbox use separate producer gates: both pins must span
publication through the native wake call, and shutdown waits for admitted producers.
Stream tracks direction and file cursor, Group tracks member results, and Dispatcher
forwards a consumed result to its bound observers. A race can be ready while its losing
operations still borrow buffers; cancel and consume them until the group is settled before
reusing its storage. These adapters do not own the Loop or its native resources.
Runtime state belongs to explicit instances. The sole process-wide mutable-state exception is an atomic gate that serializes Unix descriptor inheritance setup against library-managed process creation across independent loops. Making this gate local to a loop would allow a child process to inherit another loop's descriptor before close-on-exec is set.
If the HTTP server's completion poll fails during shutdown, the server retains outstanding
I/O and worker storage until retirement. It reports through on_diagnostic and retries with exponential
backoff capped at one second. The standalone native I/O worker pool instead records the
first failure and yields before retrying. Persistent backend failure can delay shutdown
indefinitely; neither releases memory that native work can still access.
Run the in-memory board on loopback (default port 8080, or pass another nonzero port):
zig build run-board
zig build run-board -- 8081Open http://127.0.0.1:8080/, adjusting the port if needed. The page and its JavaScript and
CSS are embedded in the executable. The browser creates tasks with POST /api/tasks,
toggles them with PATCH /api/tasks/:id, and deletes them with DELETE /api/tasks/:id.
Successful changes reload the page; errors appear inline. The API also supports
GET /api/tasks and GET /api/tasks/:id. PATCH accepts a title update even though the page
has no rename control.
The board stores up to 64 tasks in memory; restarting resets them. Its bounded store lock allows concurrent app API calls, but does not provide persistence. Route handlers run on the I/O loop. The request body limit is 2 KiB, the in-flight request limit is 256, and the framework memory budget is 128 MiB.
Stop the foreground process with Ctrl+C. The example does not expose a remote shutdown endpoint or configure cross-thread shutdown control.
zig build check
zig build testOptional check: zig build check-extras compiles additional I/O examples.
zig build test also runs public I/O integration contracts with an explicit native backend:
epoll on Linux, iocp on Windows, and kqueue on macOS/FreeBSD. Run them independently or
select another backend with:
zig build test-io -Dio-backend=epoll
zig build test-io -Dio-backend=uring
zig build test-io -Dio-backend=iocp
zig build test-io -Dio-backend=kqueueRun each command on a compatible host. Explicit selections never fall back. Unavailable
backends fail by default; -Dio-allow-unavailable=true explicitly skips them.
Skipped tests are not runtime coverage. CI is configured for Linux, Windows, and macOS;
FreeBSD needs a native run.
Use -Doptimize=ReleaseSafe for the optimized safety build and -Dio-test-filter=TCP to run
only matching I/O tests.
Run the I/O consumer examples with:
zig build io-examples io-pipeline
zig build io-runtime -- 2MIT.