fediglam/src/main/main.zig

72 lines
1.9 KiB
Zig
Raw Normal View History

2022-04-02 20:23:18 +00:00
const std = @import("std");
2022-07-10 22:19:21 +00:00
const builtin = @import("builtin");
2022-07-09 22:07:51 +00:00
const http = @import("http");
2022-07-10 05:05:01 +00:00
// this thing is overcomplicated and weird. stop this
const Router = http.Router(*RequestServer);
const Route = Router.Route;
const RouteArgs = http.RouteArgs;
const router = Router{
.routes = &[_]Route{
2022-07-10 22:19:21 +00:00
Route.new(.GET, "/healthcheck", healthcheck),
2022-07-10 05:05:01 +00:00
},
};
2022-07-10 22:19:21 +00:00
const json_options = if (builtin.mode == .Debug)
.{
.whitespace = .{
.indent = .{ .Space = 2 },
.separator = true,
},
} else .{
.whitespace = .{
.indent = .None,
.separator = false,
},
};
2022-07-10 05:05:01 +00:00
2022-07-10 22:19:21 +00:00
fn healthcheck(srv: *RequestServer, ctx: *http.server.Context, _: RouteArgs) !void {
2022-07-10 05:05:01 +00:00
const alloc = srv.alloc;
const headers = http.Headers.init(alloc);
var stream = try ctx.openResponse(&headers, .ok);
defer stream.close();
2022-07-10 22:19:21 +00:00
const writer = stream.writer();
try std.json.stringify(.{ .status = "ok" }, json_options, writer);
2022-07-10 05:05:01 +00:00
try stream.finish();
}
2022-04-23 07:11:40 +00:00
const RequestServer = struct {
2022-07-10 05:05:01 +00:00
alloc: std.mem.Allocator,
fn init(alloc: std.mem.Allocator) RequestServer {
return RequestServer{
.alloc = alloc,
};
}
fn listenAndRun(self: *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
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
var ctx = srv.accept(alloc) catch unreachable;
defer ctx.close();
2022-04-21 09:34:04 +00:00
2022-07-10 05:05:01 +00:00
router.dispatch(self, &ctx, ctx.request.method, ctx.request.path) catch unreachable;
}
}
};
pub fn main() anyerror!void {
2022-07-10 05:05:01 +00:00
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var srv = RequestServer.init(gpa.allocator());
srv.listenAndRun(std.net.Address.parseIp("0.0.0.0", 8080) catch unreachable);
2022-05-20 04:46:39 +00:00
}