better(ish)

This commit is contained in:
Jeeves 2024-03-25 17:36:13 -06:00
parent f0f072ebab
commit 224157889a

View file

@ -4,48 +4,43 @@ const net = std.net;
const http = std.http;
const heap = std.heap;
const App = Listener(Router);
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var router = Router.init(allocator, &handle, &handleError);
defer router.deinit();
// var router = Router.init(allocator, &handle, &handleError);
// defer router.deinit();
try router.addRoute("/", &handle);
// try router.addRoute("/", &handle);
const address = try net.Address.parseIp("0.0.0.0", 8080);
var listener = App.init(.{
var listener = Listener.init(.{
.address = address,
.allocator = allocator,
.context = router,
.handler = router.handle,
// .handler = router.handle,
.handler = &handle,
});
defer listener.deinit();
try listener.listen();
}
pub fn handle(_: *Router, event: *App.Event) anyerror!void {
pub fn handle(event: *Listener.Event) anyerror!void {
try event.res.body.appendSlice("hello there");
}
pub fn handleError(_: Router, event: *App.Event) anyerror!void {
pub fn handleError(event: *Listener.Event) anyerror!void {
try event.res.body.appendSlice("ahoy, an error occurred");
}
pub fn Listener(comptime Context: type) type {
return struct {
pub const Listener = struct {
address: net.Address,
arena: heap.ArenaAllocator,
ctx: *Context,
handlerFn: HandlerFn,
pub const Options = struct {
address: net.Address,
allocator: mem.Allocator,
context: *Context,
handler: HandlerFn,
};
@ -53,7 +48,6 @@ pub fn Listener(comptime Context: type) type {
return .{
.address = options.address,
.arena = heap.ArenaAllocator.init(options.allocator),
.ctx = options.context,
.handlerFn = options.handler,
};
}
@ -95,7 +89,7 @@ pub fn Listener(comptime Context: type) type {
var header_it = req.iterateHeaders();
while (header_it.next()) |header| try event.req.headers.append(&header);
try self.handlerFn(self.ctx, &event);
try self.handlerFn(&event);
try self.respondFromEvent(&event, &req);
}
@ -129,11 +123,9 @@ pub fn Listener(comptime Context: type) type {
};
};
pub const HandlerFn = *const fn (ctx: *Context, event: *Event) anyerror!void;
};
}
pub const HandlerFn = *const fn (event: *Event) anyerror!void;
pub const Router = struct {
pub const Router = struct {
allocator: mem.Allocator,
root_node: Node,
@ -195,6 +187,5 @@ pub const Router = struct {
pub const Type = enum { normal, wildcard, placeholder };
};
pub const HandlerFn = *const fn (self: *Router, event: *App.Event) anyerror!void;
};
};