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.
.openssl = true
within the
build.zig
dependency like shown above.