Networking and HTTP

40.1 TCP with std.net

// Server
const address = try std.net.Address.parseIp("127.0.0.1", 9000);
var server = try address.listen(.{ .reuse_address = true });
defer server.deinit();
while (true) {
    const conn = try server.accept();
    defer conn.stream.close();
    var buf: [1024]u8 = undefined;
    const n = try conn.stream.read(&buf);
    _ = try conn.stream.write(buf[0..n]);         // echo
}

// Client
const stream = try std.net.tcpConnectToHost(allocator, "example.com", 80);
defer stream.close();
_ = try stream.write("GET / HTTP/1.0\r\nHost: example.com\r\n\r\n");

40.2 HTTP Client (std.http.Client)

Built-in TLS 1.2/1.3 client (std.crypto.tls). std.http.Server provides low-level server building blocks.

The HTTP APIs changed significantly in 0.15 (they're built on the new Reader/Writer). Verify against your version.

var client: std.http.Client = .{ .allocator = allocator };
defer client.deinit();
var body = std.Io.Writer.Allocating.init(allocator);
defer body.deinit();
const res = try client.fetch(.{
    .location = .{ .url = "https://ziglang.org" },
    .method = .GET,
    .response_writer = &body.writer,
});
std.debug.print("status {d}, {d} bytes\n", .{ @intFromEnum(res.status), body.written().len });

40.3 Web Frameworks and Libraries

http.zig (httpz) Fast HTTP/1.1 server with a thread pool, routing, middleware, websockets Wraps facil.io: very fast, mature

Full-stack MVC framework (templates, routing, jobs) built on httpz DI-based server framework WebSocket client/server zzz / tardy Async runtime + HTTP

pg.zig, zqlite, zig-sqlite, myzql PostgreSQL, SQLite, MySQL drivers

// http.zig example
const httpz = @import("httpz");
pub fn main() !void {
    var gpa: std.heap.DebugAllocator(.{}) = .init;
    const allocator = gpa.allocator();
    var server = try httpz.Server(void).init(allocator, .{ .port = 8080 }, {});
    defer server.deinit();
    var router = try server.router(.{});
    router.get("/hello/:name", hello, .{});
    try server.listen();
}
fn hello(req: *httpz.Request, res: *httpz.Response) !void {
    try res.json(.{ .greeting = req.param("name").? }, .{});
}