2022-04-02 20:23:18 +00:00
|
|
|
const std = @import("std");
|
2022-07-09 22:07:51 +00:00
|
|
|
const http = @import("http");
|
2022-04-23 07:11:40 +00:00
|
|
|
|
2022-07-10 01:01:03 +00:00
|
|
|
const RequestServer = struct {
|
|
|
|
fn listenAndRun(_: *RequestServer, addr: std.net.Address) noreturn {
|
|
|
|
var srv = http.Server.listen(addr) catch unreachable;
|
|
|
|
defer srv.shutdown();
|
2022-04-04 03:36:32 +00:00
|
|
|
|
2022-07-10 01:01:03 +00:00
|
|
|
while (true) {
|
|
|
|
var buf: [1 << 20]u8 = undefined;
|
|
|
|
var fba = std.heap.FixedBufferAllocator.init(&buf);
|
|
|
|
const alloc = fba.allocator();
|
2022-04-02 20:23:18 +00:00
|
|
|
|
2022-07-10 01:01:03 +00:00
|
|
|
var ctx = srv.accept(alloc) catch unreachable;
|
|
|
|
defer ctx.close();
|
2022-04-21 09:34:04 +00:00
|
|
|
|
2022-07-10 01:01:03 +00:00
|
|
|
handleRequest(alloc, &ctx) catch unreachable;
|
|
|
|
}
|
|
|
|
}
|
2022-04-02 20:23:18 +00:00
|
|
|
|
2022-07-10 01:01:03 +00:00
|
|
|
fn handleRequest(alloc: std.mem.Allocator, ctx: *http.server.Context) !void {
|
2022-07-09 22:07:51 +00:00
|
|
|
const headers = http.Headers.init(alloc);
|
2022-04-02 20:23:18 +00:00
|
|
|
|
2022-07-09 22:07:51 +00:00
|
|
|
var stream = try ctx.openResponse(&headers, .ok);
|
|
|
|
const writer = stream.writer();
|
|
|
|
defer stream.close();
|
2022-07-10 01:01:03 +00:00
|
|
|
|
|
|
|
try writer.print("Page for {s}\n", .{ctx.request.path});
|
|
|
|
if (ctx.request.body) |body| {
|
|
|
|
try writer.print("Echoing body: \n{s}", .{body});
|
|
|
|
}
|
2022-05-20 04:46:39 +00:00
|
|
|
|
2022-07-09 22:07:51 +00:00
|
|
|
try stream.finish();
|
|
|
|
}
|
2022-07-10 01:01:03 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
pub fn main() anyerror!void {
|
|
|
|
var srv = RequestServer{};
|
|
|
|
srv.listenAndRun(std.net.Address.parseIp("0.0.0.0", 8080) catch unreachable);
|
2022-05-20 04:46:39 +00:00
|
|
|
}
|