Skip to content

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.

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/echo
You sent 10 bytes: Zig is fun
$ curl -i http://127.0.0.1:8080/nope
HTTP/1.1 404 Not Found
content-length: 17
content-type: text/plain; charset=utf-8
Nothing at /nope

And the server logs every request:

listening on http://127.0.0.1:8080
GET / -> 200
GET /hello?name=Ada%20Lovelace -> 200
POST /echo -> 200
GET /nope -> 404

What 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).

Make a folder with one file, server.zig:

Terminal window
mkdir webserver
cd webserver

You’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.

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:

Terminal window
zig run server.zig

and in the second, ask for a page. -i tells curl to show the response’s header lines too:

Terminal window
curl -i http://127.0.0.1:8080/hello

curl shows the response:

HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 13
Connection: 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.1 means “this computer only”, so nobody else on your network can connect. 8080 is the port; any free number above 1024 works without admin rights.
  • address.listen(io, ...) opens the listening socket, and server.accept(io) waits until a client connects, then returns a Stream for that one connection.
  • stream.reader(io, &buffer) and stream.writer(io, &buffer) give you the same buffered reader and writer as for files and stdin, so takeDelimiter, writeAll and flush work 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:

Terminal window
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 OK
connection: close
content-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, or receiveHead fails with error.HttpHeadersOversize. 8 KB is plenty for normal requests.
  • receiveHead() reads and parses the head. request.head.method is an enum (.GET, .POST, …) and request.head.target is 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 next accept.
  • Errors from one visitor are printed and skipped with catch, never try. A server that exits because one client sent nonsense would be easy to knock over. (Sending that with nc here printed bad 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 /echo
GET /hello?name=Ada%20Lovelace -> 200 Hello, Ada Lovelace!
GET /hello -> 200 Hello, stranger!
POST /echo -> 200 You sent 10 bytes: Zig is fun
GET /echo -> 405 use POST here
GET /nope -> 404 Nothing at /nope

How route works:

  • std.mem.cutScalar(u8, target, '?') splits /hello?name=Ada into the path /hello and the query name=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.Status has a name for every status code, and @backingInt turns one into its number for printing.
  • HEAD is treated like GET: it means “just the headers, please”, and respond leaves the body out by itself.
  • queryValue walks the key=value pairs separated by &. Browsers and curl encode special characters in addresses (a space is %20), so std.Uri.percentDecodeInPlace turns them back into the real text. It decodes in place, so it works on a copy made with arena.dupe.
  • arena.print builds 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 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:

Terminal window
nc 127.0.0.1 8080

Now, in a third terminal:

Terminal window
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) starts serveConnection(io, gpa, stream) so that it runs at the same time as the accept loop. The default init.io runs it on another thread.
  • It’s concurrent, not async, on purpose. async is allowed to run the function right away, before returning, and that’s the one thing a server loop can’t afford. concurrent either really runs it alongside, or fails with error.ConcurrencyUnavailable (Zig Async & Futures explains the difference).
  • If it fails, the catch serves 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.

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:

Terminal window
zig run server.zig

and 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. No free calls, and a long-running server can’t slowly leak. A tool that exits after a moment can use init.arena instead, 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, receiveHead returns error.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 an Expect: 100-continue header). 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 with error.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 inside Head”). So serveRequest copies target into 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.

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.

  • A visit counter. Add /count, which answers how many requests the server has handled. Keep the number in a global std.atomic.Value(u32) and use fetchAdd, since many connections may bump it at once.
  • Serve files. Map /static/<name> to files in a public folder with std.Io.Dir.cwd().openDir(...) and readFileAlloc, and set the content-type from the extension. Reject names containing .. so nobody can read files outside the folder.
  • JSON. Make /hello?name=Ada answer {"greeting":"Hello, Ada!"} with std.json from Zig JSON, and set content-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, so test blocks with std.testing.expectEqualStrings can check every route (Zig Testing).
  • A client in Zig. std.http.Client sends 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), listen and accept give you a Stream per client, with the usual buffered reader and writer.
  • std.http.Server.init(reader, writer), receiveHead() and respond(body, .{ .status = ... }) do the parsing and the headers for you.
  • Put the decisions in a pure route function so you can try every path without a network.
  • Use an arena per request with reset(.retain_capacity), limit body sizes, and copy head strings before reading the body.
  • Serve clients concurrently with a std.Io.Group and group.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

1. What separates the headers of an HTTP request from its body?
2. Why does the server use group.concurrent instead of group.async for each connection?
3. Why does serveRequest copy request.head.target before reading a POST body?
4. What does arena_state.reset(.retain_capacity) at the start of each request do?