const std = @import("std"); const builtin = @import("builtin"); const http = @import("http"); const util = @import("util"); const api = @import("./api.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(.POST, "/auth/register", c.auth.register), Route.new(.POST, "/auth/login", c.auth.login), Route.new(.GET, "/auth/authenticate", c.auth.authenticate), Route.new(.POST, "/notes", c.notes.create), Route.new(.GET, "/notes/:id", c.notes.get), Route.new(.GET, "/notes/:id/reacts", c.notes.reacts.list), Route.new(.POST, "/notes/:id/reacts", c.notes.reacts.create), Route.new(.GET, "/actors/:id", c.actors.get), }, }; 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) { const buf = try self.alloc.alloc(u8, 1 << 28); // 4mb defer self.alloc.free(buf); 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()); api.initThreadPrng(@bitCast(u64, std.time.milliTimestamp())); return srv.listenAndRun(std.net.Address.parseIp("0.0.0.0", 8080) catch unreachable); }