Contact Info

sean [at] coreitpro [dot] com gpg key

Mastodon

sc68cal on Libera

Zig Http Client Learning

Did some programming tonight, just learning more Zig and playing around with the std.http.Client

It may be that I’m still learning my way around but I do find the documentation to still be a little on the sparse side. Maybe I’m just spoiled by requests because I do also remember the bad old days of Python and using urllib and urllib2 directly and those were pretty awful APIs too.

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    var client = std.http.Client{ .allocator = allocator };
    defer client.deinit();

    var header_buffer: [1024]u8 = undefined;

    const uri = try std.Uri.parse("https://ifconfig.me/ip");
    var req = try client.open(std.http.Method.GET, uri, .{ .server_header_buffer = &header_buffer });
    defer req.deinit();
    try req.send();
    try req.finish();
    try req.wait();

    std.debug.print("Status={}\n", .{req.response.status});
    std.debug.print("Size={}\n", .{req.response.content_length.?});

    const resp_body = try allocator.alloc(u8, req.response.content_length.?);
    defer allocator.free(resp_body);

    _ = try req.readAll(resp_body);
    std.debug.print("Respone Body={s}\n", .{resp_body});
}

const std = @import("std");