Getting Started

Start by creating a new 0.13.0 Zig project and changing into the new directory.

$ mkdir hello-world
$ cd hello-world
$ zig init

Add Zap as a dependency to build.zig.zon

$ mkdir hello-world
$ zig fetch --save "git+https://github.com/zigzap/zap#v0.9.0"

Add Zap to build.zig

const zap = b.dependency("zap", .{
    .target = target,
    .optimize = optimize,
    .openssl = false, // set to true to enable TLS support
});
exe.root_module.addImport("zap", zap.module("zap"));

Replace the contents of src/main.zig with the following. Note: The complete source code for this example can be found here.

const std = @import("std");
const zap = @import("zap");

fn on_request(r: zap.Request) void {
    if (r.path) |the_path| {
        std.debug.print("PATH: {s}\n", .{the_path});
    }

    if (r.query) |the_query| {
        std.debug.print("QUERY: {s}\n", .{the_query});
    }

    r.sendBody("<html><body><h1>Hello from ZAP!!!</h1></body></html>") catch return;
}

pub fn main() !void {
    var listener = zap.HttpListener.init(.{
        .port = 3000,
        .on_request = on_request,
        .log = true,
        .max_clients = 100000,
    });
    try listener.listen();

    std.debug.print("Listening on 0.0.0.0:3000\n", .{});

    zap.start(.{
        .threads = 2,
        .workers = 1, // 1 worker enables sharing state between threads
    });
}

That's it! Build and run the program, then go to http://127.0.0.1:3000/

$ zig build run

For more examples, check out the repo here.

FAQ

  • Q: Does Zap support Zig master?
    • A: See the zig-master branch. Please note that the zig-master branch is not the official master branch of Zap until Zig 0.14.0 is released.
  • Q: Does ZAP work on Windows?
    • A: No. This is due to the underlying facil.io C library. Future versions of facil.io might support Windows but there is no timeline yet. Your best options on Windows are WSL2 or a docker container.
  • Q: Does ZAP support TLS / HTTPS?
    • A: Yes, ZAP supports using the system's openssl. See the https example for more information. You must set .openssl = true within the build.zig dependency like shown above.
  • Q: Where is the API documentation?
    • Docs are a work in progress. You can check them out here.