Separate request handling and acceptance
This commit is contained in:
parent
013bc015c5
commit
5fc8b99051
1 changed files with 24 additions and 11 deletions
|
@ -1,27 +1,40 @@
|
|||
const std = @import("std");
|
||||
const http = @import("http");
|
||||
|
||||
//const db = @import("./db.zig");
|
||||
const RequestServer = struct {
|
||||
fn listenAndRun(_: *RequestServer, addr: std.net.Address) noreturn {
|
||||
var srv = http.Server.listen(addr) catch unreachable;
|
||||
defer srv.shutdown();
|
||||
|
||||
pub fn main() anyerror!void {
|
||||
var srv = try http.Server.listen(std.net.Address.parseIp("0.0.0.0", 8080) catch unreachable);
|
||||
defer srv.shutdown();
|
||||
while (true) {
|
||||
var buf: [1 << 20]u8 = undefined;
|
||||
var fba = std.heap.FixedBufferAllocator.init(&buf);
|
||||
const alloc = fba.allocator();
|
||||
|
||||
while (true) {
|
||||
var buf: [1 << 20]u8 = undefined;
|
||||
var fba = std.heap.FixedBufferAllocator.init(&buf);
|
||||
var ctx = srv.accept(alloc) catch unreachable;
|
||||
defer ctx.close();
|
||||
|
||||
const alloc = fba.allocator();
|
||||
var ctx = try srv.accept(alloc);
|
||||
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);
|
||||
|
||||
var stream = try ctx.openResponse(&headers, .ok);
|
||||
const writer = stream.writer();
|
||||
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();
|
||||
}
|
||||
};
|
||||
|
||||
pub fn main() anyerror!void {
|
||||
var srv = RequestServer{};
|
||||
srv.listenAndRun(std.net.Address.parseIp("0.0.0.0", 8080) catch unreachable);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue