Skip to content

Instantly share code, notes, and snippets.

@lizard-demon
Created July 8, 2026 09:59
Show Gist options
  • Select an option

  • Save lizard-demon/84caf488193efdd64e759dd1297d4d9d to your computer and use it in GitHub Desktop.

Select an option

Save lizard-demon/84caf488193efdd64e759dd1297d4d9d to your computer and use it in GitHub Desktop.
Zig 0.16.0 file downloader demo
const std = @import("std");
const Io = std.Io;
pub fn main(init: std.process.Init) !u8 {
const alloc = init.arena.allocator();
const args = try init.minimal.args.toSlice(alloc);
if (args.len < 2 or args.len > 3) return 2;
const u = try std.Uri.parse(args[1]);
const dest = if (args.len == 3) args[2] else Io.Dir.path.basenamePosix(u.path.percent_encoded);
if (dest.len == 0) return 2;
var th: Io.Threaded = .init(init.gpa, .{});
defer th.deinit();
const io = th.io();
var c: std.http.Client = .{ .allocator = init.gpa, .io = io };
defer c.deinit();
// 1. Probe size
var req = try c.request(.HEAD, u, .{});
defer req.deinit();
try req.sendBodiless();
var hbuf: [4096]u8 = undefined;
const sz = (try req.receiveHead(&hbuf)).head.content_length orelse 0;
// 2. Open file
var fd = try Io.Dir.cwd().createFile(io, dest, .{});
defer fd.close(io);
// 3. Execute
_ = (Download(10){ .io = io, .c = &c, .u = u, .fd = fd }).run(sz) catch return 1;
return 0;
}
pub fn Download(comptime W: usize) type {
return struct {
io: Io,
c: *std.http.Client,
u: std.Uri,
fd: Io.File,
const Self = @This();
pub fn run(self: Self, sz: u64) !void {
// Stream if unknown or under 5MB threshold
if (sz < 5 * 1024 * 1024) return self.stream();
var f: [W]Io.Future(anyerror!void) = undefined;
const n = @min(sz, W);
var off: u64 = 0;
for (0..n) |i| {
const len = (sz / n) + @intFromBool(i < sz % n);
f[i] = try self.io.concurrent(chunk, .{ self, off, off + len - 1 });
off += len;
}
for (f[0..n]) |*wait| try wait.await(self.io);
}
fn stream(self: Self) !void {
var fbuf: [64 * 1024]u8 = undefined;
var w = self.fd.writer(self.io, &fbuf);
_ = try self.c.fetch(.{
.location = .{ .uri = self.u },
.response_writer = &w.interface
});
}
fn chunk(self: Self, st: u64, en: u64) anyerror!void {
var fbuf: [64 * 1024]u8 = undefined;
var w = self.fd.writer(self.io, &fbuf);
try w.seekTo(st);
var rbuf: [64]u8 = undefined;
const rng = try std.fmt.bufPrint(&rbuf, "bytes={d}-{d}", .{ st, en });
_ = try self.c.fetch(.{
.location = .{ .uri = self.u },
.response_writer = &w.interface,
.extra_headers = &.{.{ .name = "Range", .value = rng }},
});
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment