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.
Fetching a URL
Section titled “Fetching a URL”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.Clientis a plain struct: set.allocatorand.io, anddeinitit when you’re done. It keeps connections open between requests, so make one client and reuse it.std.Io.Writer.Allocatingis a writer that grows a buffer as bytes arrive.fetchwrites the response body into it, andbody.written()gives you the bytes. (Any*std.Io.Writerworks here, for example a file writer to download straight to disk. Zig Interfaces explains why.)fetchtakes an options struct:.locationis the URL,.response_writeris where the body goes. Leave out.response_writerif you only care about the status. Add.method = .POSTand.payload = "..."to send data.result.statusis an enum,std.http.Status.{t}prints its name (ok,not_found), and@backingIntgives the number (200, 404).
HTTPS just works: Zig’s standard library has its own TLS code and loads your system’s trusted certificates.
A 404 is not an error
Section titled “A 404 is not an error”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.
A tiny HTTP server
Section titled “A tiny HTTP server”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):
curl -i http://127.0.0.1:8080/curl http://127.0.0.1:8080/hello/Anacurl -i http://127.0.0.1:8080/nopeYou’ll see:
HTTP/1.1 200 OKcontent-length: 16
Hello from Zig!Hi, Ana!HTTP/1.1 404 Not Foundcontent-length: 10
Not foundAnd the server’s own terminal logs each request:
listening on http://127.0.0.1:8080GET /GET /hello/AnaGET /nopePress 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.1only accepts connections from your own machine, which is what you want while learning.0.0.0.0would accept them from your whole network.listenopens the port..reuse_address = truelets you restart the server right away; without it, the port can stay “in use” for a minute after you stop it.acceptwaits 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.initwraps the stream’s reader and writer and speaks HTTP over them.receiveHead()reads one request’s first line and headers;request.head.targetis the path, andrequest.head.methodisGET,POSTand so on.request.respond(body, options)writes the status line, headers and body, and flushes. Options include.statusand.extra_headers.- The inner loop handles keep-alive: a browser often sends several requests on one connection. When the client closes it,
receiveHeadfails and webreakto accept the next one.
Answering with JSON
Section titled “Answering with JSON”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 OKcontent-length: 30content-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.
The client and the server, together
Section titled “The client and the server, together”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 okbody: 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.
Practice
Section titled “Practice”1. A status checker
Section titled “1. A status checker”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:
./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 1http://127.0.0.1:8080/: 200 okhttp://127.0.0.1:8080/nope: 404 not_foundhttp://127.0.0.1:8080/: ConnectionRefusednot a url: InvalidFormatExit codes make it useful in scripts, like ./status https://example.com/ || echo "site is down". Zig CLI Tools goes deeper into that.
2. Count the visits
Section titled “2. Count the visits”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.Clientneeds an allocator andio;client.fetch(.{ .location = .{ .url = ... } })makes a request, HTTPS included.- Collect the body with a
std.Io.Writer.Allocatingpassed as.response_writer. - A 404 is not an error: check
result.statusyourself. Errors mean the request didn’t happen (ConnectionRefused,InvalidFormat, …). - A server is
IpAddress.parse,listen,accept, thenstd.http.Server.initover 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- std.http.Client source (0.17.1):
fetch,FetchOptionsand the lower-levelrequestAPI. - std.http.Server source (0.17.1):
receiveHead,respond, streaming responses and WebSockets. - Zig 0.16.0 release notes: Networking: how networking moved into
std.Ioin 0.16. - MDN: An overview of HTTP: how requests, responses, status codes and headers work.