When working with HTTP requests in Zig, retrieving and printing response headers can be straightforward with the standard library. Here’s a concise example demonstrating how to perform a GET request and list the response headers from https://ziglang.org/
.
pub fn print_headers(allocator: std.mem.Allocator) !void {
const writer = std.io.getStdOut().writer();
var bw = std.io.bufferedWriter(writer);
const uri = try std.Uri.parse("https://ziglang.org/");
var buf: [4096]u8 = undefined;
var client = std.http.Client{
.allocator = allocator,
};
defer client.deinit();
const start = std.time.milliTimestamp();
var req = try client.open(.GET, uri, .{ .server_header_buffer = &buf });
defer req.deinit();
try req.send();
try req.finish();
try req.wait();
const stop = std.time.milliTimestamp();
try writer.print("Status: {d}, Duration: {d}\n", .{ req.response.status, stop - start });
var responseHeadersIterator = req.response.iterateHeaders();
while (responseHeadersIterator.next()) |header| {
try writer.print("{s}: {s}\n", .{ header.name, header.value });
}
try bw.flush();
}
Output
Status: http.Status.ok, Duration: 249
Server: nginx/1.18.0
Date: Fri, 02 May 2025 20:04:34 GMT
Content-Type: text/html
Last-Modified: Fri, 02 May 2025 14:22:36 GMT
Transfer-Encoding: chunked
Connection: keep-alive
ETag: W/"6814d52c-37c8"
Content-Encoding: gzip