forked from zigzap/zap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.zig
72 lines (60 loc) · 2.27 KB
/
main.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
65
66
67
68
69
70
71
72
const std = @import("std");
const zap = @import("zap");
const UserWeb = @import("userweb.zig");
const StopEndpoint = @import("stopendpoint.zig");
// this is just to demo that we can catch arbitrary slugs
fn on_request(r: zap.Request) void {
if (r.path) |the_path| {
std.debug.print("REQUESTED PATH: {s}\n", .{the_path});
}
r.sendBody("<html><body><h1>Hello from ZAP!!!</h1></body></html>") catch return;
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{
.thread_safe = true,
}){};
var allocator = gpa.allocator();
// we scope everything that can allocate within this block for leak detection
{
// setup listener
var listener = zap.Endpoint.Listener.init(
allocator,
.{
.port = 3000,
.on_request = on_request,
.log = true,
.public_folder = "examples/endpoint/html",
.max_clients = 100000,
.max_body_size = 100 * 1024 * 1024,
},
);
defer listener.deinit();
// /users endpoint
var userWeb = UserWeb.init(allocator, "/users");
defer userWeb.deinit();
var stopEp = StopEndpoint.init("/stop");
// register endpoints with the listener
try listener.register(userWeb.endpoint());
try listener.register(stopEp.endpoint());
// fake some users
var uid: usize = undefined;
uid = try userWeb.users().addByName("renerocksai", null);
uid = try userWeb.users().addByName("renerocksai", "your mom");
// listen
try listener.listen();
std.debug.print("Listening on 0.0.0.0:3000\n", .{});
// and run
zap.start(.{
.threads = 2000,
// IMPORTANT! It is crucial to only have a single worker for this example to work!
// Multiple workers would have multiple copies of the users hashmap.
//
// Since zap is quite fast, you can do A LOT with a single worker.
// Try it with `zig build run-endpoint -Drelease-fast`
.workers = 1,
});
}
// show potential memory leaks when ZAP is shut down
const has_leaked = gpa.detectLeaks();
std.log.debug("Has leaked: {}\n", .{has_leaked});
}