😺

【Zig】TCP サーバーを HTTP/1 対応にする

2024/07/12に公開

Zig 0.13.0 で確認。std.net.Address.listenstd.net.Server を生成する

const std = @import("std");
const net = std.net;
const print = std.debug.print;

pub fn main() !void {
  const loopback = try net.Ip4Address.parse("127.0.0.1", 8000);
  const localhost = net.Address{ .in = loopback };
  var server = try localhost.listen(.{
    .reuse_port = true,
  });
  defer server.deinit();

  print("serving http://localhost:{}\r\n", .{ 8000 });

  const data = "HTTP/1.1 200 OK\r\n" ++
    "Content-Type: text/html; charset=UTF-8\r\n" ++
    "Content-Length: 13\r\n" ++
    "Connection: Close\r\n" ++
    "\r\n" ++
    "Hello World\r\n";

  while (true) {
    var conn = try server.accept();
    defer conn.stream.close();
    var writer = conn.stream.writer();
    _ = try writer.writeAll(data);
  }

}

Discussion