Split out json printing code

This commit is contained in:
jaina heartles 2022-07-10 17:01:36 -07:00
parent 685dc13455
commit 9c2bd11526

View file

@ -27,33 +27,32 @@ const json_options = if (builtin.mode == .Debug)
}, },
}; };
fn getNote(srv: *RequestServer, ctx: *http.server.Context, _: RouteArgs) !void { // Responds to a request with a json value
const alloc = srv.alloc; fn respondJson(ctx: *http.server.Context, value: anytype, alloc: std.mem.Allocator) !void {
const headers = http.Headers.init(alloc); var headers = http.Headers.init(alloc);
defer headers.deinit();
const note = try db.getNote(alloc); // Don't need to free this k/v pair because they aren't dynamically allocated
defer db.free(alloc, note); try headers.put("Content-Type", "application/json");
var stream = try ctx.openResponse(&headers, .ok); var stream = try ctx.openResponse(&headers, .ok);
defer stream.close(); defer stream.close();
const writer = stream.writer(); const writer = stream.writer();
try std.json.stringify(note, json_options, writer); try std.json.stringify(value, json_options, writer);
try stream.finish(); 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 { fn healthcheck(srv: *RequestServer, ctx: *http.server.Context, _: RouteArgs) !void {
const alloc = srv.alloc; try respondJson(ctx, .{ .status = "ok" }, 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 { const RequestServer = struct {