Skip to content

Instantly share code, notes, and snippets.

@masakielastic
Last active March 4, 2026 06:33
Show Gist options
  • Select an option

  • Save masakielastic/3e4b63a8d9376dc722a9b478f12507f7 to your computer and use it in GitHub Desktop.

Select an option

Save masakielastic/3e4b63a8d9376dc722a9b478f12507f7 to your computer and use it in GitHub Desktop.
Zig 0.15.2 で HTTP クライアント

Zig 0.15.2 で HTTP クライアント

zig run client.zig
const std = @import("std");
fn makeMemWriter(buf: []u8) std.Io.Writer {
const W = std.Io.Writer;
const Vt = W.VTable;
const Adapter = struct {
fn drain(w: *W, chunks: []const []const u8, start: usize) error{WriteFailed}!usize {
var written: usize = 0;
var i: usize = start;
while (i < chunks.len) : (i += 1) {
const data = chunks[i];
const avail = w.buffer.len - w.end;
if (data.len > avail) return error.WriteFailed;
@memcpy(w.buffer[w.end .. w.end + data.len], data);
w.end += data.len;
written += data.len;
}
return written;
}
fn flush(_: *W) error{WriteFailed}!void {}
fn rebase(_: *W, _: usize, _: usize) error{WriteFailed}!void {}
fn sendFile(_: *W, _: *std.fs.File.Reader, _: std.Io.Limit)
error{EndOfStream, ReadFailed, Unimplemented, WriteFailed}!usize
{
return error.Unimplemented;
}
};
const vt = Vt{
.drain = Adapter.drain,
.sendFile = Adapter.sendFile,
.flush = Adapter.flush,
.rebase = Adapter.rebase,
};
return W{ .vtable = &vt, .buffer = buf, .end = 0 };
}
fn writeStatusLine(file: *std.fs.File, status: std.http.Status) !void {
var line: [12]u8 = undefined;
line[0..8].* = "Status: ".*;
const code: u16 = @intFromEnum(status);
line[8] = @as(u8, '0') + @as(u8, @intCast(code / 100));
line[9] = @as(u8, '0') + @as(u8, @intCast((code / 10) % 10));
line[10] = @as(u8, '0') + @as(u8, @intCast(code % 10));
line[11] = '\n';
try file.writeAll(&line);
}
pub fn main() !void {
const allocator = std.heap.page_allocator;
var stdout_file = std.fs.File.stdout();
var client = std.http.Client{ .allocator = allocator };
defer client.deinit();
// 受信ボディ保存先
var body_buf: [256 * 1024]u8 = undefined;
var body_writer = makeMemWriter(&body_buf);
// ★ここを変える:localhost のポート
const url = "http://127.0.0.1:8080/";
const res = try client.fetch(.{
.location = .{ .url = url },
.method = .GET,
.keep_alive = false,
.response_writer = &body_writer,
});
try writeStatusLine(&stdout_file, res.status);
try stdout_file.writeAll(body_buf[0..body_writer.end]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment