iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😺

[Zig] Making a TCP Server HTTP/1 Compatible

に公開

Tested with Zig 0.13.0. Create a std.net.Server using std.net.Address.listen.

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