aboutsummaryrefslogtreecommitdiff
path: root/src/routes/fallback.zig
blob: 78d778b3051ac83a94053fcf2e7b7cfeaa1a12a9 (plain)
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
31
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 });
        }
    }
}