Skip to content

Instantly share code, notes, and snippets.

@softprops
Created October 20, 2024 22:17
Show Gist options
  • Save softprops/9c86e142d0804148b071d97fbf6a971d to your computer and use it in GitHub Desktop.
Save softprops/9c86e142d0804148b071d97fbf6a971d to your computer and use it in GitHub Desktop.
zig server
const std = @import("std");
pub fn main() !void {
try serve(8008, handle);
}
fn serve(port: u16, handler: fn (*std.http.Server.Request) void) !void {
var addr = try std.net.Address.parseIp("127.0.0.1", port);
var svr = try addr.listen(.{});
defer svr.deinit();
std.debug.print("listening @ {any}\n", .{addr});
while (true) {
var conn = svr.accept() catch |err| {
std.debug.print("Failed to accept connection: {any}\n", .{err});
continue;
};
defer conn.stream.close();
var buf: [1024 * 4]u8 = undefined;
var server = std.http.Server.init(conn, &buf);
var req = server.receiveHead() catch |err| {
std.debug.print("Failed to receive request head: {any}\n", .{err});
continue;
};
handler(&req);
}
}
fn handle(req: *std.http.Server.Request) void {
std.debug.print("Received request for {s} {s}\n", .{ @tagName(req.head.method), req.head.target });
req.respond("Hello, Zig HTTP server!", .{}) catch |err| {
std.debug.print("Failed to receive request head: {any}\n", .{err});
return;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment