🎃

【Zig】http.Server で HTTP/1 サーバーをつくる

2024/07/12に公開

Zig 0.13.0 で確認。とりあえず動くが curl で複数回リクエストするとクラッシュしてしまう

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

// https://ziglang.org/download/0.12.0/release-notes.html#Rework-Server-Entirely

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

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

  var buffer:[1024] u8 = undefined;
  var send_buffer:[1024] u8 = undefined;

  while (true) {
    var conn = try http_server.accept();
    defer conn.stream.close();

    var server = http.Server.init(conn, &buffer);

    while (server.state == .ready) {
      var request = try server.receiveHead();
      var response =  request.respondStreaming(.{ .send_buffer = &send_buffer });
      _ = try response.write("Hello World\r\n");
      try response.end();
    }

  }

}

レスポンスは次のように書くこともできる

_ = try request.respond("Hello World\r\n", .{});

クラッシュしたときのエラーメッセージも記録に残しておく

/home/masakielastic/.local/share/mise/installs/zig/0.13.0/lib/std/http/Server.zig:98:17: 0x130dd04 in receiveHead (server)
                return error.HttpConnectionClosing;
                ^
/home/masakielastic/zig-project/server.zig:26:21: 0x130c52a in main (server)
      var request = try server.receiveHead();

Discussion