Manage memory for responses using arenas or writers
masterAny memory allocated for a response (like the body or headers) must remain valid until after the action returns. You have two primary ways to handle this:
- Use
res.arena: This is a fast, thread-local buffer that falls back to anstd.heap.ArenaAllocator. It is the recommended first option for data that only needs to live until the action exits. - Use
res.writer(): You can write directly to the response stream. Onceres.write()returns, the response is sent and you can safely clean up resources.
Note: When using res.writer(), you must provide a buffer (e.g., &.{}) to align with the *std.Io.Writer interface in Zig 0.15.
fn arenaExample(req: *httpz.Request, res: *httpz.Response) !void {
const query = try req.query();
const name = query.get("name") orelse "stranger";
res.body = try std.fmt.allocPrint(res.arena, "Hello {s}", .{name});
}
fn writerExample(req: *httpz.Request, res: *httpz.Response) !void {
const query = try req.query();
const name = query.get("name") orelse "stranger";
try std.fmt.format(res.writer(&.{}), "Hello {s}", .{name});
}