zzz is a networking framework (HTTP) that allows for modularity and flexibility in design. For most use cases, this flexibility is not a requirement and so various defaults are provided.
For this guide, we will assume that you are running on a supported platform. This is the current latest release.
zig fetch --save git+https://github.com/mookums/zzz#v0.3.0
We can write a quick example that serves out "Hello, World" responses to any client that connects to the server. This example is derived from the one that is provided within the examples/basic
directory.
const std = @import("std");
const log = std.log.scoped(.@"examples/basic");
const zzz = @import("zzz");
const http = zzz.HTTP;
const tardy = zzz.tardy;
const Tardy = tardy.Tardy(.auto);
const Runtime = tardy.Runtime;
const Socket = tardy.Socket;
const Server = http.Server;
const Router = http.Router;
const Context = http.Context;
const Route = http.Route;
const Respond = http.Respond;
fn base_handler(_: *const Context, _: void) !Respond {
return Respond{ .standard = .{
.status = .OK,
.mime = http.Mime.HTML,
.body = "Hello, world!",
} };
}
pub fn main() !void {
const host: []const u8 = "0.0.0.0";
const port: u16 = 9862;
var gpa = std.heap.GeneralPurposeAllocator(.{ .thread_safe = true }){};
const allocator = gpa.allocator();
defer _ = gpa.deinit();
var t = try Tardy.init(allocator, .{ .threading = .single });
defer t.deinit();
var router = try Router.init(allocator, &.{
Route.init("/").get({}, base_handler).layer(),
}, .{});
defer router.deinit(allocator);
// create socket for tardy
var socket = try Socket.init(.{ .tcp = .{ .host = host, .port = port } });
defer socket.close_blocking();
try socket.bind();
try socket.listen(256);
const EntryParams = struct {
router: *const Router,
socket: Socket,
};
try t.entry(
EntryParams{ .router = &router, .socket = socket },
struct {
fn entry(rt: *Runtime, p: EntryParams) !void {
var server = Server.init(rt.allocator, .{
.stack_size = 1024 * 1024 * 4,
.socket_buffer_bytes = 1024 * 2,
.keepalive_count_max = null,
.connection_count_max = 10,
});
try server.serve(rt, p.router, p.socket);
}
}.entry,
);
}
The snippet above handles all of the basic tasks involved with serving a plaintext route using zzz's HTTP implementation.