1
0
Fork 0
mirror of https://github.com/zigzap/zap.git synced 2025-10-21 07:34:08 +00:00

fixed hello_json example

This commit is contained in:
Rene Schallner 2023-01-13 16:30:34 +01:00
parent 0a29e52764
commit 655d3c0d5d

View file

@ -19,7 +19,7 @@ fn on_request(r: zap.SimpleRequest) void {
const user = users.get(user_id); const user = users.get(user_id);
var json_to_send: []const u8 = undefined; var json_to_send: []const u8 = undefined;
if (JsonHelper.stringify(user, .{})) |json| { if (stringify(user, .{})) |json| {
json_to_send = json; json_to_send = json;
} else { } else {
json_to_send = "null"; json_to_send = "null";
@ -39,12 +39,9 @@ fn setupUserData(a: std.mem.Allocator) !void {
try users.put(2, .{ .first_name = "Your", .last_name = "Mom" }); try users.put(2, .{ .first_name = "Your", .last_name = "Mom" });
} }
const JsonHelper = struct { fn stringify(value: anytype, options: std.json.StringifyOptions) ?[]const u8 {
// "static" instance of buffer
var buf: [100]u8 = undefined; var buf: [100]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buf); var fba = std.heap.FixedBufferAllocator.init(&buf);
fn stringify(value: anytype, options: std.json.StringifyOptions) ?[]const u8 {
var string = std.ArrayList(u8).init(fba.allocator()); var string = std.ArrayList(u8).init(fba.allocator());
if (std.json.stringify(value, options, string.writer())) { if (std.json.stringify(value, options, string.writer())) {
return string.items; return string.items;
@ -52,7 +49,6 @@ const JsonHelper = struct {
return null; return null;
} }
} }
};
pub fn main() !void { pub fn main() !void {
var a = std.heap.page_allocator; var a = std.heap.page_allocator;