aboutsummaryrefslogtreecommitdiff
path: root/src/routes/root.zig
blob: 01952bb7758608d5ac4d19a0dc6a312aa99896e3 (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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const std = @import("std");

pub const fallback = @import("fallback.zig");
pub const login = @import("login.zig");

pub const HandlerInfo = struct {
    handler: *const fn (
                 request: *std.http.Server.Request,
                 allocator: std.mem.Allocator,
             ) anyerror!void,
    needs_auth: bool,
    method: std.http.Method,

    pub fn handle(
        self: *const @This(),
        request: *std.http.Server.Request,
        allocator: std.mem.Allocator,
    ) !void {
        if (request.head.method != self.method) {
            try request.respond("{ \"error\": \"Bad Request\" }", .{ .status = .bad_request });
        }

        self.handler(request, allocator) catch |err| {
            const response, const status_code: std.http.Status = switch (err) {
                error.BadRequest => .{ "{ \"error\": \"Bad Request\" }", .bad_request },
                error.Unauthorized => .{ "{ \"error\": \"Unauthorized\" }", .unauthorized },
                error.Forbidden => .{ "{ \"error\": \"Forbidden\" }", .forbidden },
                error.NotFound => .{ "{ \"error\": \"Not Found\" }", .not_found },
                else => .{ "{ \"error\": \"Internal Server Error\" }", .internal_server_error },
            };

            try request.respond(response, .{ .status = status_code });
        };
    }
};

pub const handlers = std.StaticStringMap(HandlerInfo).initComptime(.{
    .{
        "",
        HandlerInfo {
            .handler = fallback.handler,
            .needs_auth = false,
            .method = .GET,
        }
    },
    .{
        "/api/login",
        HandlerInfo {
            .handler = login.handler,
            .needs_auth = false,
            .method = .POST,
        }
    },
});

pub fn get(path: []const u8) HandlerInfo {
    return (handlers.getLongestPrefix(std.mem.trimEnd(u8, path, "/")) orelse unreachable).value;
}