zig std: use threads for the http server

This commit is contained in:
Andrew Kelley 2024-03-06 18:00:34 -07:00
parent c7c7ad1b78
commit 574b33e65a

View file

@ -36,26 +36,34 @@ pub fn main() !void {
.zig_lib_directory = zig_lib_directory,
};
var read_buffer: [8000]u8 = undefined;
accept: while (true) {
while (true) {
const connection = try http_server.accept();
_ = std.Thread.spawn(.{}, accept, .{ &context, connection }) catch |err| {
std.log.err("unable to accept connection: {s}", .{@errorName(err)});
connection.stream.close();
continue;
};
}
}
fn accept(context: *Context, connection: std.net.Server.Connection) void {
defer connection.stream.close();
var read_buffer: [8000]u8 = undefined;
var server = std.http.Server.init(connection, &read_buffer);
while (server.state == .ready) {
var request = server.receiveHead() catch |err| switch (err) {
error.HttpConnectionClosing => continue :accept,
error.HttpConnectionClosing => return,
else => {
std.log.err("closing http connection: {s}", .{@errorName(err)});
continue :accept;
return;
},
};
serveRequest(&request, &context) catch |err| {
serveRequest(&request, context) catch |err| {
std.log.err("unable to serve {s}: {s}", .{ request.head.target, @errorName(err) });
continue :accept;
return;
};
}
}
}
const Context = struct {