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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Serves the generated API documentation over HTTP, the way `zig std` serves//! the standard library's.//!//! A server is needed rather than just opening `index.html`, because the//! viewer fetches `sources.tar` and `main.wasm` at runtime and a browser//! refuses those requests from a `file://` page.//!//! Run it through the build system: `zig build docs-serve`. It is//! deliberately minimal, serving one directory to one person on the loopback//! interface — it is a convenience for reading `zig build docs`, not a web//! server, and nothing about it should be pointed at a network.//!//! It is built on this repository's own library, which is worth being//! deliberate about. A project that ships an HTTP server and then reaches for//! somebody else's to serve its own documentation has said something about//! its library that no README can take back. It is also the most useful test//! there is: this is a second real consumer of the API, doing the thing most//! consumers will do — resolving a path and sending a file — and a browser is//! a far less forgiving client than a test suite.
const std = @import("std");const Io = std.Io;
const http = @import("http");const http_io = @import("http_io");const Request = http.server.Request;const Response = http.server.Response;
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const args = try init.minimal.args.toSlice(init.arena.allocator());
var stderr_buffer: [512]u8 = undefined; var stderr_writer: Io.File.Writer = .init(.stderr(), init.io, &stderr_buffer); const stderr = &stderr_writer.interface;
if (args.len != 3) { try stderr.writeAll("usage: docs-server <directory> <port>\n"); try stderr.flush(); std.process.exit(2); } const docs_path = args[1]; const port = try std.fmt.parseInt(u16, args[2], 10);
// A browser opens several connections at once and holds some of them open // without sending anything, so a server that reads them one at a time // waits on a speculative connection and never answers the real requests. var threaded: Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io();
var docs = Docs{ .dir = Io.Dir.cwd().openDir(io, docs_path, .{}) catch |err| { try stderr.print("cannot open {s}: {s}\n", .{ docs_path, @errorName(err) }); try stderr.flush(); std.process.exit(1); }, }; defer docs.dir.close(io);
var listener = http_io.tcp.Listener.listen( io, .{ .ip4 = .{ .bytes = .{ 127, 0, 0, 1 }, .port = port } }, .{}, ) catch |err| { try stderr.print("cannot listen on 127.0.0.1:{d}: {s}\n", .{ port, @errorName(err) }); if (err == error.AddressInUse) { try stderr.writeAll("another port can be chosen with -Ddocs-port=N\n"); } try stderr.flush(); std.process.exit(1); }; defer listener.deinit(io);
var server: http.server.Server = .init(io, gpa, listener.listener(), .init(&docs, Docs.serve), .{ // `sources.tar` is the big one, and the buffer is how much of it // leaves in a single write. .listener = .{ .write_buffer_len = 64 * 1024 }, .http1 = .{ .body_write_buffer_len = 64 * 1024 }, });
try stderr.print( "serving {s} at http://127.0.0.1:{d}/\npress ctrl-c to stop\n", .{ docs_path, port }, ); try stderr.flush();
try server.serve();}
const Docs = struct { dir: Io.Dir,
/// The longest path this will look up. The documentation bundle's names /// are all short; anything longer is somebody probing. const max_path_len = 512;
fn serve(d: *Docs, req: *Request, res: *Response) anyerror!void { if (!req.method.eql(.get) and !req.method.eql(.head)) { try res.setHeader("Allow", "GET, HEAD"); return res.sendStatus(.method_not_allowed); }
// The resolver is what keeps this inside the documentation directory: // it decodes each segment on its own, refuses one that decodes to // something holding a separator or a NUL, and refuses a `..` with // nothing left to leave. Without it, `GET /../../etc/passwd` would be // a file this happily opens. var path_buf: [max_path_len]u8 = undefined; const resolved = req.target.resolvePath(&path_buf) catch return res.sendStatus(.bad_request);
var name_buf: [max_path_len + "index.html".len]u8 = undefined; const name = if (resolved[resolved.len - 1] == '/') std.fmt.bufPrint(&name_buf, "{s}index.html", .{resolved[1..]}) catch return res.sendStatus(.uri_too_long) else resolved[1..];
var file = d.dir.openFile(req.io, name, .{}) catch return res.sendStatus(.not_found); defer file.close(req.io);
const stat = file.stat(req.io) catch return res.sendStatus(.internal_server_error); if (stat.kind != .file) return res.sendStatus(.not_found);
try res.setHeader("Content-Type", mimeType(name)); // The length is known, so the response is not chunked and the browser // gets a progress bar. A `HEAD` gets exactly this head and no octets, // without the handler having to know which it is answering. const body = try res.beginBody(.{ .exact = stat.size });
var read_buffer: [64 * 1024]u8 = undefined; var file_reader = file.reader(req.io, &read_buffer); _ = body.sendFileAll(&file_reader, .unlimited) catch return error.SendFileFailed; return res.end(); }};
/// Enough of a MIME table for what `zig build docs` emits.fn mimeType(path: []const u8) []const u8 { const extension = std.fs.path.extension(path); const table = [_]struct { []const u8, []const u8 }{ .{ ".html", "text/html; charset=utf-8" }, .{ ".js", "text/javascript; charset=utf-8" }, .{ ".css", "text/css; charset=utf-8" }, .{ ".wasm", "application/wasm" }, .{ ".tar", "application/x-tar" }, .{ ".json", "application/json" }, .{ ".svg", "image/svg+xml" }, }; for (table) |entry| { if (std.mem.eql(u8, extension, entry[0])) return entry[1]; } return "application/octet-stream";}
const testing = std.testing;
test mimeType { try testing.expectEqualStrings("text/html; charset=utf-8", mimeType("index.html")); try testing.expectEqualStrings("application/wasm", mimeType("main.wasm")); try testing.expectEqualStrings("application/x-tar", mimeType("sources.tar")); try testing.expectEqualStrings("text/javascript; charset=utf-8", mimeType("main.js")); try testing.expectEqualStrings("application/octet-stream", mimeType("noextension"));}