Separate request handling and acceptance

This commit is contained in:
jaina heartles 2022-07-09 18:01:03 -07:00
parent 013bc015c5
commit 5fc8b99051

View file

@ -1,27 +1,40 @@
const std = @import("std"); const std = @import("std");
const http = @import("http"); const http = @import("http");
//const db = @import("./db.zig"); const RequestServer = struct {
fn listenAndRun(_: *RequestServer, addr: std.net.Address) noreturn {
pub fn main() anyerror!void { var srv = http.Server.listen(addr) catch unreachable;
var srv = try http.Server.listen(std.net.Address.parseIp("0.0.0.0", 8080) catch unreachable);
defer srv.shutdown(); defer srv.shutdown();
while (true) { while (true) {
var buf: [1 << 20]u8 = undefined; var buf: [1 << 20]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buf); var fba = std.heap.FixedBufferAllocator.init(&buf);
const alloc = fba.allocator(); const alloc = fba.allocator();
var ctx = try srv.accept(alloc);
var ctx = srv.accept(alloc) catch unreachable;
defer ctx.close(); defer ctx.close();
handleRequest(alloc, &ctx) catch unreachable;
}
}
fn handleRequest(alloc: std.mem.Allocator, ctx: *http.server.Context) !void {
const headers = http.Headers.init(alloc); const headers = http.Headers.init(alloc);
var stream = try ctx.openResponse(&headers, .ok); var stream = try ctx.openResponse(&headers, .ok);
const writer = stream.writer(); const writer = stream.writer();
defer stream.close(); defer stream.close();
try writer.print("Page for {s}", .{ctx.request.path});
try writer.print("Page for {s}\n", .{ctx.request.path});
if (ctx.request.body) |body| {
try writer.print("Echoing body: \n{s}", .{body});
}
try stream.finish(); try stream.finish();
} }
};
pub fn main() anyerror!void {
var srv = RequestServer{};
srv.listenAndRun(std.net.Address.parseIp("0.0.0.0", 8080) catch unreachable);
} }