aboutsummaryrefslogtreecommitdiff
path: root/src/routes
diff options
context:
space:
mode:
Diffstat (limited to 'src/routes')
-rw-r--r--src/routes/fallback.zig32
-rw-r--r--src/routes/root.zig15
2 files changed, 47 insertions, 0 deletions
diff --git a/src/routes/fallback.zig b/src/routes/fallback.zig
new file mode 100644
index 0000000..78d778b
--- /dev/null
+++ b/src/routes/fallback.zig
@@ -0,0 +1,32 @@
+const std = @import("std");
+const http = @import("../http.zig");
+
+const log = std.log.scoped(.fallback);
+
+pub fn handler(
+ request: *std.http.Server.Request,
+ allocator: std.mem.Allocator,
+) anyerror!void {
+ var static = try std.fs.cwd().openDir("static", .{});
+ defer static.close();
+
+ if (static.openFile(request.head.target[1..], .{})) |file| {
+ defer file.close();
+ try http.respond_file(request, file, request.head.target[1..], allocator);
+ } else |_| {
+ var subdir = if (request.head.target.len == 1) static
+ else (static.openDir(request.head.target[1..], .{}) catch {
+ try request.respond("Not Found", .{ .status = .not_found });
+ return;
+ });
+ defer if (request.head.target.len > 1) subdir.close();
+
+ if (subdir.openFile("index.html", .{})) |file| {
+ defer file.close();
+ try http.respond_file(request, file, "index.html", allocator);
+ } else |_| {
+ log.warn("File '{s}' Not Found", .{ request.head.target });
+ try request.respond("Not Found", .{ .status = .not_found });
+ }
+ }
+}
diff --git a/src/routes/root.zig b/src/routes/root.zig
new file mode 100644
index 0000000..0330404
--- /dev/null
+++ b/src/routes/root.zig
@@ -0,0 +1,15 @@
+const std = @import("std");
+
+pub const fallback = @import("fallback.zig");
+
+pub const Handler = *const fn (
+ request: *std.http.Server.Request,
+ allocator: std.mem.Allocator,
+) anyerror!void;
+
+pub const handlers = std.StaticStringMap(Handler).initComptime(.{
+});
+
+pub fn get(path: []const u8) Handler {
+ return handlers.get(path) orelse fallback.handler;
+}