Skip to content

Zig Networking & HTTP

Zig’s standard library can talk HTTP on its own: there’s a client that fetches URLs (HTTPS included) and a server you can answer requests with, no packages needed. They’re fairly low-level compared to Python’s requests or Node’s express, so you see every step, which makes this a good place to learn how HTTP actually works. This page fetches a real web page, builds a small web server, and then points the two at each other.

The client is std.http.Client. You give it an allocator and io, and call fetch:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var client: std.http.Client = .{ .allocator = gpa, .io = init.io };
defer client.deinit();
var body: std.Io.Writer.Allocating = .init(gpa);
defer body.deinit();
const result = try client.fetch(.{
.location = .{ .url = "https://ziglang.org/" },
.response_writer = &body.writer,
});
const page = body.written();
std.debug.print("status: {d} ({t})\n", .{ @backingInt(result.status), result.status });
std.debug.print("{d} bytes, starting with: {s}\n", .{ page.len, page[0..@min(page.len, 15)] });
}

You’ll see something like:

status: 200 (ok)
12337 bytes, starting with: <!DOCTYPE html>

Step by step:

  • std.http.Client is a plain struct: set .allocator and .io, and deinit it when you’re done. It keeps connections open between requests, so make one client and reuse it.
  • std.Io.Writer.Allocating is a writer that grows a buffer as bytes arrive. fetch writes the response body into it, and body.written() gives you the bytes. (Any *std.Io.Writer works here, for example a file writer to download straight to disk. Zig Interfaces explains why.)
  • fetch takes an options struct: .location is the URL, .response_writer is where the body goes. Leave out .response_writer if you only care about the status. Add .method = .POST and .payload = "..." to send data.
  • result.status is an enum, std.http.Status. {t} prints its name (ok, not_found), and @backingInt gives the number (200, 404).

HTTPS just works: Zig’s standard library has its own TLS code and loads your system’s trusted certificates.

fetch only returns an error when the request couldn’t happen at all: bad URL, no connection, broken TLS. If the server answers “404 Not Found”, that’s a successful request with a disappointing answer, so you have to check the status yourself:

const result = try client.fetch(.{ .location = .{ .url = "https://ziglang.org/no-such-page" } });
if (result.status != .ok) {
std.debug.print("the server said {d} ({t})\n", .{ @backingInt(result.status), result.status });
return;
}

You’ll see:

the server said 404 (not_found)

The errors you’ll meet most often are error.ConnectionRefused (nothing is listening on that port), error.InvalidFormat (the URL isn’t a URL), and name-lookup errors when a host doesn’t exist. Catch them with catch |err| like any other error, as in the practice below.

Now the other side. A server needs four steps: pick an address, listen on it, accept a connection, and then read requests and write responses on that connection. In Zig 0.17, the networking parts live in std.Io.net, and the HTTP parts in std.http.Server:

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 listener = try address.listen(io, .{ .reuse_address = true });
defer listener.deinit(io);
std.debug.print("listening on http://127.0.0.1:8080\n", .{});
while (true) {
const stream = try listener.accept(io);
defer stream.close(io);
var read_buf: [4096]u8 = undefined;
var write_buf: [4096]u8 = undefined;
var reader = stream.reader(io, &read_buf);
var writer = stream.writer(io, &write_buf);
var server: std.http.Server = .init(&reader.interface, &writer.interface);
// One connection can carry several requests (keep-alive).
while (true) {
var request = server.receiveHead() catch break;
handle(&request) catch break;
}
}
}
fn handle(request: *std.http.Server.Request) !void {
const path = request.head.target;
std.debug.print("{t} {s}\n", .{ request.head.method, path });
if (std.mem.eql(u8, path, "/")) {
try request.respond("Hello from Zig!\n", .{});
} else if (std.mem.cutPrefix(u8, path, "/hello/")) |name| {
var buf: [128]u8 = undefined;
const text = std.mem.print(&buf, "Hi, {s}!\n", .{name}) catch "Hi, whoever you are!\n";
try request.respond(text, .{});
} else {
try request.respond("Not found\n", .{ .status = .not_found });
}
}

Run it with zig run server.zig, and in a second terminal, try it with curl (or open the addresses in a browser):

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

You’ll see:

HTTP/1.1 200 OK
content-length: 16
Hello from Zig!
Hi, Ana!
HTTP/1.1 404 Not Found
content-length: 10
Not found

And the server’s own terminal logs each request:

listening on http://127.0.0.1:8080
GET /
GET /hello/Ana
GET /nope

Press Ctrl+C to stop it. Here’s what each part does:

  • IpAddress.parse("127.0.0.1", 8080) is “this computer, port 8080”. 127.0.0.1 only accepts connections from your own machine, which is what you want while learning. 0.0.0.0 would accept them from your whole network.
  • listen opens the port. .reuse_address = true lets you restart the server right away; without it, the port can stay “in use” for a minute after you stop it.
  • accept waits until a client connects and returns a stream, a two-way connection. You give it a read buffer and a write buffer, the same way as stdout in Zig Readers & Writers.
  • std.http.Server.init wraps the stream’s reader and writer and speaks HTTP over them. receiveHead() reads one request’s first line and headers; request.head.target is the path, and request.head.method is GET, POST and so on.
  • request.respond(body, options) writes the status line, headers and body, and flushes. Options include .status and .extra_headers.
  • The inner loop handles keep-alive: a browser often sends several requests on one connection. When the client closes it, receiveHead fails and we break to accept the next one.

An API endpoint is the same thing with a different body and a content-type header. Add this branch to handle before the final else:

} else if (std.mem.eql(u8, path, "/api/status")) {
const Status = struct { ok: bool, version: []const u8 };
var buf: [128]u8 = undefined;
const body = try std.mem.print(&buf, "{f}", .{std.json.fmt(Status{ .ok = true, .version = "0.17.1" }, .{})});
try request.respond(body, .{
.extra_headers = &.{.{ .name = "content-type", .value = "application/json" }},
});

curl -i http://127.0.0.1:8080/api/status then gives:

HTTP/1.1 200 OK
content-length: 30
content-type: application/json
{"ok":true,"version":"0.17.1"}

std.json.fmt turns any struct into JSON as it’s printed, as shown in Zig JSON. Here it prints straight into a stack buffer, so this route doesn’t allocate at all.

With the server still running, change the URL in the fetch example to http://127.0.0.1:8080/hello/Zig and print the body:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var client: std.http.Client = .{ .allocator = gpa, .io = init.io };
defer client.deinit();
var body: std.Io.Writer.Allocating = .init(gpa);
defer body.deinit();
const result = try client.fetch(.{
.location = .{ .url = "http://127.0.0.1:8080/hello/Zig" },
.response_writer = &body.writer,
});
std.debug.print("status: {d} {t}\n", .{ @backingInt(result.status), result.status });
std.debug.print("body: {s}", .{body.written()});
}

You’ll see:

status: 200 ok
body: Hi, Zig!

And the server logs GET /hello/Zig. Two Zig programs talking HTTP with nothing but the standard library. This is also a handy way to test a server: start it, fetch from it, check the answers. The project: tiny HTTP server later builds on this.

Write a command-line tool status that takes a URL as its only argument, fetches it, prints the status, and exits with 0 for 200, 1 for anything else (including errors), and 2 if the argument is missing.

Hint: return !u8 from main. Catch fetch errors with catch |err| { ...; return 1; } and print them with {t}. You don’t need a response_writer to read the status.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !u8 {
const args = try init.minimal.args.toSlice(init.arena.allocator());
if (args.len != 2) {
std.debug.print("usage: status URL\n", .{});
return 2;
}
var client: std.http.Client = .{ .allocator = init.gpa, .io = init.io };
defer client.deinit();
const result = client.fetch(.{ .location = .{ .url = args[1] } }) catch |err| {
std.debug.print("{s}: {t}\n", .{ args[1], err });
return 1;
};
std.debug.print("{s}: {d} {t}\n", .{ args[1], @backingInt(result.status), result.status });
return if (result.status == .ok) 0 else 1;
}

With the server from this page running, then stopped, we got:

Terminal window
./status http://127.0.0.1:8080/ # exit code 0
./status http://127.0.0.1:8080/nope # exit code 1
./status http://127.0.0.1:8080/ # server stopped: exit code 1
./status "not a url" # exit code 1
http://127.0.0.1:8080/: 200 ok
http://127.0.0.1:8080/nope: 404 not_found
http://127.0.0.1:8080/: ConnectionRefused
not a url: InvalidFormat

Exit codes make it useful in scripts, like ./status https://example.com/ || echo "site is down". Zig CLI Tools goes deeper into that.

Make the server count requests and answer /count with visits: N. Keep the counter in main and pass a pointer to it into handle.

Hint: change handle to fn handle(request: *std.http.Server.Request, visits: *u32) !void, add 1 at the top, and call it as handle(&request, &visits).

Show solution

The changed parts:

// in main, before the accept loop:
var visits: u32 = 0;
// in the inner loop:
handle(&request, &visits) catch break;
// the handler:
fn handle(request: *std.http.Server.Request, visits: *u32) !void {
visits.* += 1;
const path = request.head.target;
if (std.mem.eql(u8, path, "/count")) {
var buf: [64]u8 = undefined;
const text = try std.mem.print(&buf, "visits: {d}\n", .{visits.*});
try request.respond(text, .{});
} else {
try request.respond("Hello from Zig!\n", .{});
}
}

Calling curl http://127.0.0.1:8080/ twice and then curl http://127.0.0.1:8080/count prints visits: 3. A plain counter is safe here only because this server handles one request at a time. Once requests run concurrently, it would need an atomic or a mutex, as Zig Shared State explains.

  • std.http.Client needs an allocator and io; client.fetch(.{ .location = .{ .url = ... } }) makes a request, HTTPS included.
  • Collect the body with a std.Io.Writer.Allocating passed as .response_writer.
  • A 404 is not an error: check result.status yourself. Errors mean the request didn’t happen (ConnectionRefused, InvalidFormat, …).
  • A server is IpAddress.parse, listen, accept, then std.http.Server.init over the stream’s reader and writer.
  • receiveHead() reads a request; request.respond(body, .{ ... }) answers it with a status and headers.
  • This simple server handles one connection at a time; real servers need concurrency, timeouts and limits.

Next up: Zig Game Development, opening a window and moving a square with raylib.

Quick check

1. You fetch a page and the server answers 404. What does client.fetch do?
2. How do you get the body of a response as bytes?
3. What does listener.accept(io) return?
4. Why does the example server use 127.0.0.1 instead of 0.0.0.0?