-
-
Notifications
You must be signed in to change notification settings - Fork 83
/
routes.zig
64 lines (56 loc) · 1.67 KB
/
routes.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const std = @import("std");
const zap = @import("zap");
// NOTE: this is a super simplified example, just using a hashmap to map
// from HTTP path to request function.
fn dispatch_routes(r: zap.Request) void {
// dispatch
if (r.path) |the_path| {
if (routes.get(the_path)) |foo| {
foo(r);
return;
}
}
// or default: present menu
r.sendBody(
\\ <html>
\\ <body>
\\ <p><a href="/static">static</a></p>
\\ <p><a href="/dynamic">dynamic</a></p>
\\ </body>
\\ </html>
) catch return;
}
fn static_site(r: zap.Request) void {
r.sendBody("<html><body><h1>Hello from STATIC ZAP!</h1></body></html>") catch return;
}
var dynamic_counter: i32 = 0;
fn dynamic_site(r: zap.Request) void {
dynamic_counter += 1;
var buf: [128]u8 = undefined;
const filled_buf = std.fmt.bufPrintZ(
&buf,
"<html><body><h1>Hello # {d} from DYNAMIC ZAP!!!</h1></body></html>",
.{dynamic_counter},
) catch "ERROR";
r.sendBody(filled_buf) catch return;
}
fn setup_routes(a: std.mem.Allocator) !void {
routes = std.StringHashMap(zap.HttpRequestFn).init(a);
try routes.put("/static", static_site);
try routes.put("/dynamic", dynamic_site);
}
var routes: std.StringHashMap(zap.HttpRequestFn) = undefined;
pub fn main() !void {
try setup_routes(std.heap.page_allocator);
var listener = zap.HttpListener.init(.{
.port = 3000,
.on_request = dispatch_routes,
.log = true,
});
try listener.listen();
std.debug.print("Listening on 0.0.0.0:3000\n", .{});
zap.start(.{
.threads = 2,
.workers = 2,
});
}