Minimal args parsing [0.16.0]

Hey, so I’ve been working on a CLI tool in Zig to get the hang of the language. With not many documentations out there, I kind of struggled, so I aim to share a really simple way of parsing args with the new minimal interface in the standard library. I hope it helps someone!

The way I found out about it is through this changelog example:

const std = @import("std");
const Io = std.Io;

pub fn main(init: std.process.Init) !void {
    const gpa = init.gpa;
    const io = init.io;

    // That was the reference
    const args = try init.minimal.args.toSlice(init.arena.allocator()); 

    const host_name: Io.net.HostName = try .init(args[1]);

    var http_client: std.http.Client = .{ .allocator = gpa, .io = io };
    defer http_client.deinit();

    var request = try http_client.request(.HEAD, .{
        .scheme = "http",
        .host = .{ .percent_encoded = host_name.bytes },
        .port = 80,
        .path = .{ .percent_encoded = "/" },
    }, .{});
    defer request.deinit();

    try request.sendBodiless();

    var redirect_buffer: [1024]u8 = undefined;
    const response = try request.receiveHead(&redirect_buffer);
    std.log.info("received {d} {s}", .{ response.head.status, response.head.reason });
}

It’s a pretty cool change, very simple and straightforward. If you want to dig deeper, you can check this std.init.minimal reference.

Sorry if this isn’t super detailed; I’m new to the language, but I wanted to contribute and hopefully help someone out!

2 Likes