Zig Project: HTTP Server
In this project you’ll write a small web server with nothing but Zig’s standard library. It listens on your own computer, answers a few different addresses, reads text that clients send it, and serves several visitors at the same time. You’ll talk to it with curl, the command-line tool for making web requests.
Along the way you’ll see that HTTP, the language of the web, is just lines of text sent over a connection. Once you’ve seen that, web servers stop being magic.
What you’ll build
Section titled “What you’ll build”With the finished server running in one terminal, here’s what curl gets in another:
$ curl http://127.0.0.1:8080/Welcome! Try /hello?name=Ada or POST some text to /echo$ curl "http://127.0.0.1:8080/hello?name=Ada%20Lovelace"Hello, Ada Lovelace!$ curl -d "Zig is fun" http://127.0.0.1:8080/echoYou sent 10 bytes: Zig is fun$ curl -i http://127.0.0.1:8080/nopeHTTP/1.1 404 Not Foundcontent-length: 17content-type: text/plain; charset=utf-8
Nothing at /nopeAnd the server logs every request:
listening on http://127.0.0.1:8080GET / -> 200GET /hello?name=Ada%20Lovelace -> 200POST /echo -> 200GET /nope -> 404What you’ll practise:
- Listening and accepting connections with
std.Io.net(Zig Io Interface). - Readers and writers on a network connection, the same ones you used for files (Zig Readers & Writers).
- Parsing requests and sending responses with
std.http.Server. - A pure routing function you can try without any network.
- An arena per request to keep memory simple (Zig Arena Allocator).
- Serving several clients at once with
std.Io.Group(Zig Async & Futures).
Step 1: Set up
Section titled “Step 1: Set up”Make a folder with one file, server.zig:
mkdir webservercd webserverYou’ll need two terminals for this project: one runs the server (it keeps running until you press Ctrl+C), the other runs curl. curl comes with macOS, most Linux systems and Windows 10 and later (as curl.exe). You can also open the addresses in a web browser. Everything here was checked with Zig 0.17.1 on Linux.
Step 2: HTTP is just text
Section titled “Step 2: HTTP is just text”Before using the HTTP library, let’s look at what actually arrives. This server waits for one connection, prints every line the client sends, and answers with a response written by hand:
const std = @import("std");
pub fn main(init: std.process.Init) !void { const io = init.io;
const address = try std.Io.net.IpAddress.parse("127.0.0.1", 8080); var server = try address.listen(io, .{ .reuse_address = true }); defer server.deinit(io); std.debug.print("listening on http://127.0.0.1:8080\n", .{});
// Wait for one visitor. const stream = try server.accept(io); defer stream.close(io);
var in_buffer: [4096]u8 = undefined; var conn_reader = stream.reader(io, &in_buffer); const in = &conn_reader.interface;
// Print the request, line by line, until the empty line that ends the head. while (try in.takeDelimiter('\n')) |line| { const clean = std.mem.trimEnd(u8, line, "\r"); std.debug.print("> {s}\n", .{clean}); if (clean.len == 0) break; }
// Answer with a hand-written HTTP response. var out_buffer: [1024]u8 = undefined; var conn_writer = stream.writer(io, &out_buffer); const out = &conn_writer.interface; try out.writeAll("HTTP/1.1 200 OK\r\n" ++ "Content-Type: text/plain\r\n" ++ "Content-Length: 13\r\n" ++ "Connection: close\r\n" ++ "\r\n" ++ "Hello, curl!\n"); try out.flush();}Start it in the first terminal:
zig run server.zigand in the second, ask for a page. -i tells curl to show the response’s header lines too:
curl -i http://127.0.0.1:8080/hellocurl shows the response:
HTTP/1.1 200 OKContent-Type: text/plainContent-Length: 13Connection: close
Hello, curl!and the server, before it exits, shows the request it got:
listening on http://127.0.0.1:8080> GET /hello HTTP/1.1> Host: 127.0.0.1:8080> User-Agent: curl/8.5.0> Accept: */*>That’s all HTTP is. The client sends a request line (method, path, version), some headers (Name: value), and an empty line. The server answers with a status line (200 OK), its own headers, an empty line, and the body. Every line ends with \r\n.
The Zig parts:
std.Io.net.IpAddress.parse("127.0.0.1", 8080)is the address to listen on.127.0.0.1means “this computer only”, so nobody else on your network can connect.8080is the port; any free number above 1024 works without admin rights.address.listen(io, ...)opens the listening socket, andserver.accept(io)waits until a client connects, then returns aStreamfor that one connection.stream.reader(io, &buffer)andstream.writer(io, &buffer)give you the same buffered reader and writer as for files and stdin, sotakeDelimiter,writeAllandflushwork exactly as before.- The
++joins string literals at compile time, so the whole response is one constant.
Step 3: Let std.http.Server do the parsing
Section titled “Step 3: Let std.http.Server do the parsing”Reading header lines yourself gets tricky fast: bodies, keep-alive, odd clients. std.http.Server handles that. You give it the connection’s reader and writer, call receiveHead() to get a request, and respond() to answer it. This version keeps running and answers every visitor, one after another:
const std = @import("std");
pub fn main(init: std.process.Init) !void { const io = init.io;
const address = try std.Io.net.IpAddress.parse("127.0.0.1", 8080); var server = try address.listen(io, .{ .reuse_address = true }); defer server.deinit(io); std.debug.print("listening on http://127.0.0.1:8080\n", .{});
while (true) { const stream = try server.accept(io); defer stream.close(io);
var in_buffer: [8192]u8 = undefined; var out_buffer: [8192]u8 = undefined; var conn_reader = stream.reader(io, &in_buffer); var conn_writer = stream.writer(io, &out_buffer); var http = std.http.Server.init(&conn_reader.interface, &conn_writer.interface);
var request = http.receiveHead() catch |err| { std.debug.print("bad request: {t}\n", .{err}); continue; }; std.debug.print("{t} {s}\n", .{ request.head.method, request.head.target });
request.respond("Hello from Zig!\n", .{ .keep_alive = false }) catch |err| { std.debug.print("couldn't answer: {t}\n", .{err}); }; }}Run it and try a couple of requests from the other terminal:
curl http://127.0.0.1:8080/curl -i "http://127.0.0.1:8080/anything?x=1"You’ll see:
Hello from Zig!HTTP/1.1 200 OKconnection: closecontent-length: 16
Hello from Zig!and the server prints GET / and GET /anything?x=1. Press Ctrl+C to stop it.
std.http.Server.init(reader, writer)wraps the connection. The input buffer must be big enough for the whole request head, orreceiveHeadfails witherror.HttpHeadersOversize. 8 KB is plenty for normal requests.receiveHead()reads and parses the head.request.head.methodis an enum (.GET,.POST, …) andrequest.head.targetis the path plus query string.respond(body, options)writes the status line,content-length(counted for you), any headers, the body, and flushes.defer stream.close(io)inside the loop runs at the end of each pass, so every connection is closed before the nextaccept.- Errors from one visitor are printed and skipped with
catch, nevertry. A server that exits because one client sentnonsensewould be easy to knock over. (Sending that withnchere printedbad request: HttpHeadersInvalid, and the server carried on.)
Step 4: Routes, as a function you can test
Section titled “Step 4: Routes, as a function you can test”A real server answers differently depending on the path. Let’s put that decision in one function, route, which takes the method, the target and the body, and returns a status and a body. It knows nothing about sockets, so we can try it right here with made-up requests:
const std = @import("std");
pub fn main(init: std.process.Init) !void { const arena = init.arena.allocator();
const Try = struct { std.http.Method, []const u8, []const u8 }; const tries = [_]Try{ .{ .GET, "/", "" }, .{ .GET, "/hello?name=Ada%20Lovelace", "" }, .{ .GET, "/hello", "" }, .{ .POST, "/echo", "Zig is fun" }, .{ .GET, "/echo", "" }, .{ .GET, "/nope", "" }, }; for (tries) |t| { const method, const target, const body = t; const response = try route(arena, method, target, body); std.debug.print("{t} {s} -> {d} {s}", .{ method, target, @backingInt(response.status), response.body }); }}
const Response = struct { status: std.http.Status = .ok, body: []const u8,};
/// Decides what to answer. Knows nothing about sockets, so it's easy to try out.fn route(arena: std.mem.Allocator, method: std.http.Method, target: []const u8, body: []const u8) !Response { const path, const query = std.mem.cutScalar(u8, target, '?') orelse .{ target, "" };
const is_get = method == .GET or method == .HEAD; // HEAD = GET without the body
if (std.mem.eql(u8, path, "/")) { if (!is_get) return .{ .status = .method_not_allowed, .body = "use GET here\n" }; return .{ .body = "Welcome! Try /hello?name=Ada or POST some text to /echo\n" }; } if (std.mem.eql(u8, path, "/hello")) { if (!is_get) return .{ .status = .method_not_allowed, .body = "use GET here\n" }; const name = try queryValue(arena, query, "name") orelse "stranger"; return .{ .body = try arena.print("Hello, {s}!\n", .{name}) }; } if (std.mem.eql(u8, path, "/echo")) { if (method != .POST) return .{ .status = .method_not_allowed, .body = "use POST here\n" }; return .{ .body = try arena.print("You sent {d} bytes: {s}\n", .{ body.len, body }) }; } return .{ .status = .not_found, .body = try arena.print("Nothing at {s}\n", .{path}) };}
/// Finds `key=value` in a query string like "a=1&name=Ada" and decodes %20 and friends.fn queryValue(arena: std.mem.Allocator, query: []const u8, key: []const u8) !?[]const u8 { var pairs = std.mem.splitScalar(u8, query, '&'); while (pairs.next()) |pair| { const k, const v = std.mem.cutScalar(u8, pair, '=') orelse continue; if (std.mem.eql(u8, k, key)) return std.Uri.percentDecodeInPlace(try arena.dupe(u8, v)); } return null;}Output:
GET / -> 200 Welcome! Try /hello?name=Ada or POST some text to /echoGET /hello?name=Ada%20Lovelace -> 200 Hello, Ada Lovelace!GET /hello -> 200 Hello, stranger!POST /echo -> 200 You sent 10 bytes: Zig is funGET /echo -> 405 use POST hereGET /nope -> 404 Nothing at /nopeHow route works:
std.mem.cutScalar(u8, target, '?')splits/hello?name=Adainto the path/helloand the queryname=Ada. When there’s no?,orelse .{ target, "" }uses the whole target as the path and an empty query.- Each route checks the method. Asking for a page with the wrong method gets 405 Method Not Allowed, and any unknown path gets 404 Not Found.
std.http.Statushas a name for every status code, and@backingIntturns one into its number for printing. HEADis treated likeGET: it means “just the headers, please”, andrespondleaves the body out by itself.queryValuewalks thekey=valuepairs separated by&. Browsers and curl encode special characters in addresses (a space is%20), sostd.Uri.percentDecodeInPlaceturns them back into the real text. It decodes in place, so it works on a copy made witharena.dupe.arena.printbuilds the reply text in the arena (Zig Format Strings).
The main here is a little test bench: a table of requests and a loop. When you change a route, run it again and you see every answer at a glance.
Step 5: Many visitors at once
Section titled “Step 5: Many visitors at once”Step 3’s loop serves one connection at a time. That sounds fine until one client is slow. Run Step 3’s server, then in a second terminal connect with nc (netcat) and type nothing:
nc 127.0.0.1 8080Now, in a third terminal:
curl -m 3 http://127.0.0.1:8080/curl waits three seconds and gives up (exit code 28, a timeout), because the server is stuck in receiveHead, waiting for the silent nc client to finish its request. One slow or idle client blocks everyone. In real life that’s normal: browsers keep connections open on purpose to reuse them.
The fix is to serve each connection alongside the others. In Zig 0.17 you ask your io to do that, with a std.Io.Group:
var group: std.Io.Group = .init;defer group.cancel(io);
while (true) { const stream = try server.accept(io); // Serve this visitor alongside the others. If that's not possible, serve them now. group.concurrent(io, serveConnection, .{ io, init.gpa, stream }) catch { serveConnection(io, init.gpa, stream); };}group.concurrent(io, function, args)startsserveConnection(io, gpa, stream)so that it runs at the same time as the accept loop. The defaultinit.ioruns it on another thread.- It’s
concurrent, notasync, on purpose.asyncis allowed to run the function right away, before returning, and that’s the one thing a server loop can’t afford.concurrenteither really runs it alongside, or fails witherror.ConcurrencyUnavailable(Zig Async & Futures explains the difference). - If it fails, the
catchserves the client right here, the old way. Slower, but nobody gets turned away. - The group keeps track of all running connections, and
group.cancel(io)stops them if the loop ever ends.
With this change, the nc test above no longer blocks anyone: curl gets its answer straight away while nc sits there.
Step 6: The complete program
Section titled “Step 6: The complete program”Here’s the whole server. main accepts connections and hands each one to serveConnection. serveConnection reads requests until the client is done, serveRequest reads a POST body and sends the reply, and route from Step 4 decides what the reply says:
const std = @import("std");
const port = 8080;
pub fn main(init: std.process.Init) !void { const io = init.io;
const address = try std.Io.net.IpAddress.parse("127.0.0.1", port); var server = try address.listen(io, .{ .reuse_address = true }); defer server.deinit(io); std.debug.print("listening on http://127.0.0.1:{d}\n", .{port});
var group: std.Io.Group = .init; defer group.cancel(io);
while (true) { const stream = try server.accept(io); // Serve this visitor alongside the others. If that's not possible, serve them now. group.concurrent(io, serveConnection, .{ io, init.gpa, stream }) catch { serveConnection(io, init.gpa, stream); }; }}
/// Answers every request on one connection, then closes it.fn serveConnection(io: std.Io, gpa: std.mem.Allocator, stream: std.Io.net.Stream) void { defer stream.close(io);
var in_buffer: [8192]u8 = undefined; var out_buffer: [8192]u8 = undefined; var conn_reader = stream.reader(io, &in_buffer); var conn_writer = stream.writer(io, &out_buffer); var http = std.http.Server.init(&conn_reader.interface, &conn_writer.interface);
var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit();
// One connection can carry several requests (keep-alive). while (http.reader.state == .ready) { _ = arena_state.reset(.retain_capacity); var request = http.receiveHead() catch |err| switch (err) { error.HttpConnectionClosing => return, else => { std.debug.print("bad request: {t}\n", .{err}); return; }, }; serveRequest(arena_state.allocator(), &request) catch |err| { std.debug.print("error while answering: {t}\n", .{err}); return; }; }}
fn serveRequest(arena: std.mem.Allocator, request: *std.http.Server.Request) !void { const method = request.head.method; // Copy the target now: reading the body invalidates request.head's strings. const target = try arena.dupe(u8, request.head.target);
var body: []const u8 = ""; if (method == .POST) { var body_buffer: [1024]u8 = undefined; const body_reader = try request.readerExpectContinue(&body_buffer); body = body_reader.allocRemaining(arena, .limited(64 * 1024)) catch |err| switch (err) { error.StreamTooLong => { std.debug.print("{t} {s} -> 413 (body too big)\n", .{ method, target }); return request.respond("That's too much text: the limit is 64 KB.\n", .{ .status = .payload_too_large, .keep_alive = false, }); }, else => return err, }; }
const response = try route(arena, method, target, body); std.debug.print("{t} {s} -> {d}\n", .{ method, target, @backingInt(response.status) });
try request.respond(response.body, .{ .status = response.status, .extra_headers = &.{.{ .name = "content-type", .value = "text/plain; charset=utf-8" }}, });}
const Response = struct { status: std.http.Status = .ok, body: []const u8,};
/// Decides what to answer. Knows nothing about sockets, so it's easy to try out.fn route(arena: std.mem.Allocator, method: std.http.Method, target: []const u8, body: []const u8) !Response { const path, const query = std.mem.cutScalar(u8, target, '?') orelse .{ target, "" };
const is_get = method == .GET or method == .HEAD; // HEAD = GET without the body
if (std.mem.eql(u8, path, "/")) { if (!is_get) return .{ .status = .method_not_allowed, .body = "use GET here\n" }; return .{ .body = "Welcome! Try /hello?name=Ada or POST some text to /echo\n" }; } if (std.mem.eql(u8, path, "/hello")) { if (!is_get) return .{ .status = .method_not_allowed, .body = "use GET here\n" }; const name = try queryValue(arena, query, "name") orelse "stranger"; return .{ .body = try arena.print("Hello, {s}!\n", .{name}) }; } if (std.mem.eql(u8, path, "/echo")) { if (method != .POST) return .{ .status = .method_not_allowed, .body = "use POST here\n" }; return .{ .body = try arena.print("You sent {d} bytes: {s}\n", .{ body.len, body }) }; } return .{ .status = .not_found, .body = try arena.print("Nothing at {s}\n", .{path}) };}
/// Finds `key=value` in a query string like "a=1&name=Ada" and decodes %20 and friends.fn queryValue(arena: std.mem.Allocator, query: []const u8, key: []const u8) !?[]const u8 { var pairs = std.mem.splitScalar(u8, query, '&'); while (pairs.next()) |pair| { const k, const v = std.mem.cutScalar(u8, pair, '=') orelse continue; if (std.mem.eql(u8, k, key)) return std.Uri.percentDecodeInPlace(try arena.dupe(u8, v)); } return null;}Run it:
zig run server.zigand try the requests from the top of the page in the other terminal. Every request shows up in the server’s log, like POST /echo -> 200.
The parts that are new since Step 4:
- One arena per connection, reset for each request. Everything a request allocates (the copied target, the body, the reply text) goes into the arena, and
arena_state.reset(.retain_capacity)throws it all away before the next request, while keeping the memory for reuse. Nofreecalls, and a long-running server can’t slowly leak. A tool that exits after a moment can useinit.arenainstead, like the to-do list; a server that runs for days can’t. - Keep-alive.
while (http.reader.state == .ready)keeps answering requests on the same connection. When the client closes it,receiveHeadreturnserror.HttpConnectionClosing, which is the normal way out. - Reading the body. For a POST,
request.readerExpectContinue(&body_buffer)gives a reader for the body (and answers clients that politely ask first with anExpect: 100-continueheader).allocRemaining(arena, .limited(64 * 1024))reads all of it, up to a limit, so nobody can fill your memory by sending a gigabyte. A bigger body fails witherror.StreamTooLong, and the client gets a polite 413 Payload Too Large instead. - Copying the target first.
request.head’s strings point into the input buffer, and starting to read the body is allowed to overwrite them (the doc comment says “Invalidates the string memory insideHead”). SoserveRequestcopiestargetinto the arena before it reads anything else. - Errors are logged, not fatal. A broken request or a client that disconnects halfway ends that one connection with a message. The server keeps running.
Common mistakes
Section titled “Common mistakes”Using try in the accept loop for per-client work. If serveConnection could return an error and the loop said try, one client hanging up at the wrong moment would stop the whole server. Handle every per-client error inside the client’s function.
Listening on 0.0.0.0 by accident. 0.0.0.0 means “every network interface”, so anyone on your network (or the internet, on a server) can reach it. Stick with 127.0.0.1 while you’re learning.
Two servers on one port. .reuse_address = true lets you restart the server straight after stopping it, which is why it’s here. On Linux it also lets a second copy start on the same port without any error, and then requests go to either one. If you see old behaviour after a change, check for a forgotten server in another terminal. Without the option, the second copy fails with error: AddressInUse, and so can a quick restart.
Using request.head.target after reading the body. It compiles and often looks fine, then prints garbage when a bigger body arrives. Copy what you need from head first.
Ideas to extend it
Section titled “Ideas to extend it”- A visit counter. Add
/count, which answers how many requests the server has handled. Keep the number in a globalstd.atomic.Value(u32)and usefetchAdd, since many connections may bump it at once. - Serve files. Map
/static/<name>to files in apublicfolder withstd.Io.Dir.cwd().openDir(...)andreadFileAlloc, and set thecontent-typefrom the extension. Reject names containing..so nobody can read files outside the folder. - JSON. Make
/hello?name=Adaanswer{"greeting":"Hello, Ada!"}withstd.jsonfrom Zig JSON, and setcontent-type: application/json. - Choose the port from the command line or an environment variable (Zig Command-Line Arguments).
- Write tests for
route. It’s a plain function, sotestblocks withstd.testing.expectEqualStringscan check every route (Zig Testing). - A client in Zig.
std.http.Clientsends requests too. Write a small program that calls your own server instead of curl.
- HTTP is text over a connection: a request line, headers, an empty line, maybe a body; then a status line, headers, an empty line and the body.
IpAddress.parse("127.0.0.1", port),listenandacceptgive you aStreamper client, with the usual buffered reader and writer.std.http.Server.init(reader, writer),receiveHead()andrespond(body, .{ .status = ... })do the parsing and the headers for you.- Put the decisions in a pure
routefunction so you can try every path without a network. - Use an arena per request with
reset(.retain_capacity), limit body sizes, and copyheadstrings before reading the body. - Serve clients concurrently with a
std.Io.Groupandgroup.concurrent, and handle per-client errors inside the client’s function.
Next up: Zig Project: Wrap a C Library, building a small C library with zig build and giving it a friendly Zig API.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”std.http.Serversource (0.17.1):receiveHead,respond,respondStreaming, body readers and WebSockets, with doc comments.std.Io.netsource (0.17.1): addresses,listen,accept,Streamand its reader and writer.- Networking in the 0.16.0 release notes: how networking moved into
std.Io, andGroupfor running many tasks. - The
zig stddocs server (0.17.1 source): a real server from the Zig project built the same way as this one. - An overview of HTTP (MDN): requests, responses, methods and status codes, explained from the ground up.