From 9c2bd1152689e2ff10954abc880d302c63ce79f9 Mon Sep 17 00:00:00 2001 From: jaina heartles Date: Sun, 10 Jul 2022 17:01:36 -0700 Subject: [PATCH] Split out json printing code --- src/main/main.zig | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/src/main/main.zig b/src/main/main.zig index 7a9fc0d..431adc4 100644 --- a/src/main/main.zig +++ b/src/main/main.zig @@ -27,33 +27,32 @@ const json_options = if (builtin.mode == .Debug) }, }; -fn getNote(srv: *RequestServer, ctx: *http.server.Context, _: RouteArgs) !void { - const alloc = srv.alloc; - const headers = http.Headers.init(alloc); +// Responds to a request with a json value +fn respondJson(ctx: *http.server.Context, value: anytype, alloc: std.mem.Allocator) !void { + var headers = http.Headers.init(alloc); + defer headers.deinit(); - const note = try db.getNote(alloc); - defer db.free(alloc, note); + // Don't need to free this k/v pair because they aren't dynamically allocated + try headers.put("Content-Type", "application/json"); var stream = try ctx.openResponse(&headers, .ok); defer stream.close(); const writer = stream.writer(); - try std.json.stringify(note, json_options, writer); + try std.json.stringify(value, json_options, writer); try stream.finish(); } +fn getNote(srv: *RequestServer, ctx: *http.server.Context, _: RouteArgs) !void { + const note = try db.getNote(srv.alloc); + defer db.free(srv.alloc, note); + + try respondJson(ctx, note, srv.alloc); +} + 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(); + try respondJson(ctx, .{ .status = "ok" }, srv.alloc); } const RequestServer = struct {