aboutsummaryrefslogtreecommitdiff
path: root/src/routes/static.zig
blob: f52d1782de99d9d8d7a6e79657585dfd5856aa53 (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
33
34
const std = @import("std");
const mime = @import("../mime.zig");

const memora = @import("memora");
const Context = memora.Context;

const log = std.log.scoped(.fallback);

pub const access = .everyone;

pub fn get(ctx: *Context) anyerror!memora.Stream {
    var static = try std.fs.cwd().openDir("static", .{});
    defer static.close();

    if (static.openFile(ctx.request.head.target[1..], .{})) |file| {
        const mime_type = mime.get_type(ctx.request.head.target);
        ctx.response.headers.content_type = mime_type;
        return .from_file(file);
    } else |_| {
        var subdir = if (ctx.request.head.target.len == 1) static
            else (static.openDir(ctx.request.head.target[1..], .{}) catch {
                return error.NotFound;
            });
        defer if (ctx.request.head.target.len > 1) subdir.close();

        if (subdir.openFile("index.html", .{})) |file| {
            ctx.response.headers.content_type = "text/html";
            return .from_file(file);
        } else |_| {
            log.warn("File '{s}' Not Found", .{ ctx.request.head.target });
            return error.NotFound;
        }
    }
}