const std = @import("std"); const http = @import("http"); const db = @import("./db2.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(.POST, "/object", postObject), Route.new(.GET, "/object/:id", getObject), }, }; fn postObject(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); const writer = stream.writer(); defer stream.close(); try writer.print("Page for {s}\n", .{ctx.request.path}); const id = srv.doc_db.store(ctx.request.body.?); try writer.print("{}", .{id}); try stream.finish(); } fn getObject(srv: *RequestServer, ctx: *http.server.Context, args: RouteArgs) !void { const alloc = srv.alloc; const headers = http.Headers.init(alloc); var stream = try ctx.openResponse(&headers, .ok); const writer = stream.writer(); defer stream.close(); //try writer.print("id: {s}\n", .{args.get("id").?}); const id = try std.fmt.parseInt(u64, args.get("id").?, 10); var doc_stream = (try srv.doc_db.getByLocalId(id)).?; const doc = doc_stream.reader(); var buf: [1 << 8]u8 = undefined; const count = try doc.readAll(&buf); try writer.writeAll(buf[0..count]); try stream.finish(); } const RequestServer = struct { alloc: std.mem.Allocator, doc_db: db.DocDb, fn init(alloc: std.mem.Allocator) RequestServer { return RequestServer{ .alloc = alloc, .doc_db = db.DocDb.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 unreachable; //handleRequest(alloc, &ctx) catch unreachable; } } fn handleRequest(alloc: std.mem.Allocator, ctx: *http.server.Context) !void { const headers = http.Headers.init(alloc); var stream = try ctx.openResponse(&headers, .ok); const writer = stream.writer(); defer stream.close(); try writer.print("Page for {s}\n", .{ctx.request.path}); if (ctx.request.body) |body| { try writer.print("Echoing body: \n{s}", .{body}); } try stream.finish(); } }; 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); }