aboutsummaryrefslogtreecommitdiff
path: root/src/main.zig
blob: 308d30815c96371baeb598f5186beb41a525ae0a (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
//! This is the main executable file.
//! Here we will add all cli interfaces
//! to interact with the state of the application
//! but also the actual running of the server / webapp.

const std = @import("std");
const http = @import("http");
const api = @import("api");

const site = @import("site");
const wasm = @embedFile("wasm");

const routes: http.RouteSet = .init(&([_]http.handler.Interface{
    http.handler.Static(.index, site.app.html, "text/html").interface(),
    http.handler.Static(.{"index.wasm"}, wasm, "application/wasm").interface(),
    http.handler.Static(.{"icon.png"}, @embedFile("favicon.png"), "image/png").interface(),
    images.ctx.interface(),
}) ++ api.interfaces);

const images = struct {
    const Ctx = http.handler.Context(.{ "image", .id });
    const ctx: Ctx = .{
        .get = get,
    };

    pub fn get(request: Ctx.Request) http.Response {
        const id = request.params.id.as(usize) catch return .badRequest(.string("invalid id"));

        const storage = std.Io.Dir.cwd().openDir(request.io, "storage", .{}) catch return .with(.internal_server_error, .void);
        defer storage.close(request.io);

        var allocating: std.Io.Writer.Allocating = .init(request.gpa);
        defer allocating.deinit();

        allocating.writer.print("{}.jpg", .{id}) catch return .with(.internal_server_error, .void);

        const file = storage.openFile(request.io, allocating.written(), .{}) catch return .badRequest(.string("invalid id"));

        return .ok(.file(file));
    }
};

pub fn main(init: std.process.Init) !void {
    try http.serve(init.gpa, routes, .{
        .address = try .parseLiteral("0.0.0.0:8080"),
    });
}