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(.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), Route.new(.POST, "/admin/invites", c.admin.invites.create), Route.new(.GET, "/admin/invites/:id", c.admin.invites.get), Route.new(.POST, "/admin/communities", c.admin.communities.create), Route.new(.GET, "/admin/communities/:host", c.admin.communities.get), }, }; pub const RequestServer = struct { alloc: std.mem.Allocator, api: api.ApiSource, config: Config, fn init(alloc: std.mem.Allocator, config: Config) !RequestServer { return RequestServer{ .alloc = alloc, .api = try api.ApiSource.init(alloc, config), .config = config, }; } 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 const Config = struct { host: []const u8, }; fn loadConfig(alloc: std.mem.Allocator) !Config { var file = try std.fs.cwd().openFile("config.json", .{}); defer file.close(); const bytes = try file.reader().readAllAlloc(alloc, 1 << 63); defer alloc.free(bytes); var ts = std.json.TokenStream.init(bytes); return std.json.parse(Config, &ts, .{ .allocator = alloc }); } pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const cfg = try loadConfig(gpa.allocator()); var srv = try RequestServer.init(gpa.allocator(), cfg); api.initThreadPrng(@bitCast(u64, std.time.milliTimestamp())); return srv.listenAndRun(std.net.Address.parseIp("0.0.0.0", 8080) catch unreachable); }