karlseguin / http.zig

An HTTP/1.1 server for zig
MIT License
533 stars 41 forks source link

Dispatch on all requests #49

Closed zachary822 closed 3 months ago

zachary822 commented 3 months ago

Is it possible to run the custom dispatcher on all requests (including 404 and 500)? I want to do some logging for all requests.

karlseguin commented 3 months ago

No, you have to settle for setting a custom notFound and errorHandler, and putting the logic into those.

server.notFound(notFound);
server.errorHandler(errorHandler); 
// ...

fn notFound(_: *httpz.Request, res: *httpz.Response) !void {
    res.status = 404;
    res.body = "Not Found";
}

fn errorHandler(req: *httpz.Request, res: *httpz.Response, err: anyerror) void {
    res.status = 500;
    res.body = "Internal Server Error";
    std.log.warn("httpz: unhandled exception for request: {s}\nErr: {}", .{req.url.raw, err});
}