Last active
May 9, 2025 22:43
-
-
Save doccaico/ce2efe0ec60f1ff8025734734d0041dc to your computer and use it in GitHub Desktop.
How To Make HTTP Requests(Get) in Zig (Zig version: 0.13.0-dev.46+3648d7df1)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const print = std.debug.print; | |
pub fn main() !void { | |
// Create an allocator. | |
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; | |
defer _ = gpa.deinit(); | |
const allocator = gpa.allocator(); | |
// Parse the URI. | |
const uri = try std.Uri.parse("https://example.com/"); | |
var client = std.http.Client{ .allocator = allocator }; | |
defer client.deinit(); | |
const server_header_buffer: []u8 = try allocator.alloc(u8, 1024 * 8); | |
defer allocator.free(server_header_buffer); | |
// Make the connection to the server. | |
var req = try client.open(.GET, uri, .{ | |
.server_header_buffer = server_header_buffer, | |
}); | |
defer req.deinit(); | |
try req.send(); | |
try req.finish(); | |
try req.wait(); | |
print("Response status: {d}\n\n", .{req.response.status}); | |
// Print out the headers | |
print("{s}\n", .{req.response.iterateHeaders().bytes}); | |
// Print out the headers (iterate) | |
// var it = req.response.iterateHeaders(); | |
// while (it.next()) |header| { | |
// print("{s}: {s}\n", .{ header.name, header.value }); | |
// } | |
// Read the entire response body, but only allow it to allocate 1024 * 8 of memory. | |
const body = try req.reader().readAllAlloc(allocator, 1024 * 8); | |
defer allocator.free(body); | |
// Print out the body. | |
print("{s}", .{body}); | |
} |
How to include a body?
To include a body in the payload define a body as a []const u8
to use as the payload. Update the HTTP method in the client (likely one of POST, PUT or PATCH).
Then change the sequence from:
25 try req.send();
26 try req.finish();
27 try req.wait();
to:
req.transfer_encoding = .{ .content_length = body.len };
try req.send();
var req_writer = req.writer();
try req_writer.writeAll(body);
try req.finish();
try req.wait();
This assumes that the body is a []const u8
and bound to body
variable.
Thanks for sharing @definitepotato, this was really useful.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to include a body?