much better(ish)

This commit is contained in:
Jeeves 2024-03-25 17:46:30 -06:00
parent 224157889a
commit 328391a6a3

View file

@ -18,8 +18,7 @@ pub fn main() !void {
var listener = Listener.init(.{
.address = address,
.allocator = allocator,
// .handler = router.handle,
.handler = &handle,
.root_handler = &handle,
});
defer listener.deinit();
try listener.listen();
@ -36,23 +35,25 @@ pub fn handleError(event: *Listener.Event) anyerror!void {
pub const Listener = struct {
address: net.Address,
arena: heap.ArenaAllocator,
handlerFn: HandlerFn,
router: Router,
pub const Options = struct {
address: net.Address,
allocator: mem.Allocator,
handler: HandlerFn,
root_handler: HandlerFn,
};
pub fn init(options: Options) Listener {
return .{
.address = options.address,
.arena = heap.ArenaAllocator.init(options.allocator),
.handlerFn = options.handler,
.router = Router.init(options.allocator, options.root_handler),
};
}
pub fn deinit(self: *Listener) void {
self.router.deinit();
self.arena.deinit();
}
@ -89,7 +90,7 @@ pub const Listener = struct {
var header_it = req.iterateHeaders();
while (header_it.next()) |header| try event.req.headers.append(&header);
try self.handlerFn(&event);
try self.router.handle(&event);
try self.respondFromEvent(&event, &req);
}
@ -131,9 +132,7 @@ pub const Listener = struct {
root_node: Node,
static_routes: std.StringHashMap(*Node),
error_handler: HandlerFn,
pub fn init(allocator: mem.Allocator, root_handler: HandlerFn, error_handler: HandlerFn) Router {
pub fn init(allocator: mem.Allocator, root_handler: HandlerFn) Router {
return .{
.allocator = allocator,
.root_node = .{
@ -144,16 +143,18 @@ pub const Listener = struct {
.placeholder_children = std.ArrayList(*Node).init(allocator),
},
.static_routes = std.StringHashMap(*Node).init(allocator),
.error_handler = error_handler,
};
}
pub fn deinit(self: *Router) void {
self.root_node.children.deinit();
self.root_node.placeholder_children.deinit();
self.static_routes.deinit();
}
pub fn handle(self: *Router, event: *Listener.Event) anyerror!void {
try self.route(event.req.uri.path)(self, event);
pub fn handle(self: *Router, event: *Listener.Event) !void {
const handlerFn = self.route(event.req.uri.path);
try handlerFn(event);
}
pub fn addRoute(self: *Router, path: []const u8, handler: HandlerFn) !void {
@ -173,7 +174,7 @@ pub const Listener = struct {
pub fn route(self: *Router, path: []const u8) HandlerFn {
if (self.static_routes.get(path)) |rt| return rt.handler;
if (self.root_node.wildcard_child_node) |node| return node.handler;
return self.error_handler;
return self.root_node.handler;
}
pub const Node = struct {