forked from karlseguin/http.zig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathglobal.zig
30 lines (26 loc) · 989 Bytes
/
global.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
const std = @import("std");
const httpz = @import("httpz");
const Allocator = std.mem.Allocator;
// Our global state
const GlobalContext = struct {
hits: usize = 0,
l: std.Thread.Mutex = .{},
pub fn increment(self: *GlobalContext, _: *httpz.Request, res: *httpz.Response) !void {
self.l.lock();
const hits = self.hits + 1;
self.hits = hits;
self.l.unlock();
res.content_type = httpz.ContentType.TEXT;
res.body = try std.fmt.allocPrint(res.arena, "{d} hits", .{hits});
}
};
// Started in main.zig which starts 3 servers, on 3 different ports, to showcase
// small variations in using httpz.
pub fn start(allocator: Allocator) !void {
var ctx = GlobalContext{};
var server = try httpz.ServerCtx(*GlobalContext, *GlobalContext).init(allocator, .{ .port = 5883 }, &ctx);
defer server.deinit();
var router = server.router();
router.get("/increment", GlobalContext.increment);
return server.listen();
}