Split out json printing code

This commit is contained in:
jaina heartles 2022-07-10 17:01:36 -07:00
parent 685dc13455
commit 9c2bd11526
1 changed files with 15 additions and 16 deletions

View File

@ -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 {