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, "/auth/authenticate", c.authenticate), Route.new(.GET, "/notes/:id", c.getNote), Route.new(.POST, "/notes", c.createNote), Route.new(.GET, "/notes/:id/reacts", c.listReacts), Route.new(.POST, "/notes/:id/reacts", c.react), 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) !void { 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 = try srv.accept(alloc); 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 => return err, }; } } }; pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var srv = try RequestServer.init(gpa.allocator()); return srv.listenAndRun(std.net.Address.parseIp("0.0.0.0", 8080) catch unreachable); }