Add 404 route

This commit is contained in:
jaina heartles 2022-05-19 20:19:54 -07:00
parent f891aeafa7
commit 126ab9a57b

View file

@ -11,6 +11,7 @@ pub fn Router(comptime Context: type) type {
};
routes: []const Route,
route_404: H,
pub fn dispatch(self: *const Self, path: []const u8, ctx: Context) void {
for (self.routes) |r| {
@ -18,7 +19,8 @@ pub fn Router(comptime Context: type) type {
return r.handler(ctx);
}
}
unreachable;
return self.route_404(ctx);
}
};
}
@ -53,6 +55,7 @@ const _tests = struct {
const mock_a = CallTracker(.{}, dummyHandler);
const mock_b = CallTracker(.{}, dummyHandler);
const mock_c = CallTracker(.{}, dummyHandler);
const mock_404 = CallTracker(.{}, dummyHandler);
const R = Router(Context).Route;
const routes = [_]R{
@ -61,20 +64,29 @@ const _tests = struct {
.{ .handler = mock_c.func, .path = "/c" },
};
const router = Router(Context){ .routes = &routes };
const router = Router(Context){ .routes = &routes, .route_404 = mock_404.func };
router.dispatch("/a", .{});
try mock_a.expectCalled(1);
try mock_b.expectCalled(0);
try mock_c.expectCalled(0);
try mock_404.expectCalled(0);
router.dispatch("/b", .{});
try mock_a.expectCalled(1);
try mock_b.expectCalled(1);
try mock_c.expectCalled(0);
try mock_404.expectCalled(0);
router.dispatch("/a", .{});
try mock_a.expectCalled(2);
try mock_b.expectCalled(1);
try mock_c.expectCalled(0);
try mock_404.expectCalled(0);
router.dispatch("/abcd", .{});
try mock_a.expectCalled(2);
try mock_b.expectCalled(1);
try mock_c.expectCalled(0);
try mock_404.expectCalled(1);
}
};