const std = @import("std"); const builtin = @import("builtin"); const http = @import("http"); // 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", healthcheck), }, }; const json_options = if (builtin.mode == .Debug) .{ .whitespace = .{ .indent = .{ .Space = 2 }, .separator = true, }, } else .{ .whitespace = .{ .indent = .None, .separator = false, }, }; fn healthcheck(srv: *RequestServer, ctx: *http.server.Context, _: RouteArgs) !void { const alloc = srv.alloc; const headers = http.Headers.init(alloc); var stream = try ctx.openResponse(&headers, .ok); defer stream.close(); const writer = stream.writer(); try std.json.stringify(.{ .status = "ok" }, json_options, writer); try stream.finish(); } const RequestServer = struct { alloc: std.mem.Allocator, fn init(alloc: std.mem.Allocator) RequestServer { return RequestServer{ .alloc = 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 unreachable; } } }; pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var srv = RequestServer.init(gpa.allocator()); srv.listenAndRun(std.net.Address.parseIp("0.0.0.0", 8080) catch unreachable); }