fediglam/src/main/main.zig

62 lines
1.9 KiB
Zig

const std = @import("std");
const builtin = @import("builtin");
const http = @import("http");
const util = @import("util");
const api = @import("./api.zig");
const models = @import("./models.zig");
const Uuid = util.Uuid;
const c = @import("./controllers.zig");
// this thing is overcomplicated and weird. stop this
const Router = http.Router(*RequestServer);
const Route = Router.Route;
const RouteArgs = http.RouteArgs;
const router = Router{
.routes = &[_]Route{
Route.new(.GET, "/healthcheck", c.healthcheck),
Route.new(.GET, "/notes/:id", c.getNote),
Route.new(.POST, "/notes", c.createNote),
Route.new(.GET, "/users/:id", c.getUser),
Route.new(.POST, "/users", c.createUser),
},
};
pub const RequestServer = struct {
alloc: std.mem.Allocator,
api: api.ApiServer,
fn init(alloc: std.mem.Allocator) !RequestServer {
return RequestServer{
.alloc = alloc,
.api = try api.ApiServer.init(alloc),
};
}
fn listenAndRun(self: *RequestServer, addr: std.net.Address) noreturn {
var srv = http.Server.listen(addr) catch unreachable;
defer srv.shutdown();
while (true) {
var buf: [1 << 20]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buf);
const alloc = fba.allocator();
var ctx = srv.accept(alloc) catch unreachable;
defer ctx.close();
router.dispatch(self, &ctx, ctx.request.method, ctx.request.path) catch |err| switch (err) {
error.NotFound, error.RouteNotApplicable => c.notFound(self, &ctx),
else => unreachable,
};
}
}
};
pub fn main() anyerror!void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var srv = try RequestServer.init(gpa.allocator());
srv.listenAndRun(std.net.Address.parseIp("0.0.0.0", 8080) catch unreachable);
}