Support zig 0.14.0 and zap 0.10.1, fix memory management issue.

This commit is contained in:
Madeorsk 2025-04-12 12:15:37 +02:00
parent 6b0d21da60
commit 90eb7ea55a
Signed by: Madeorsk
GPG key ID: 677E51CA765BB79F
3 changed files with 27 additions and 20 deletions

View file

@ -28,8 +28,16 @@ pub const RoutingResult = struct {
// Move bytes from the end to the beginning of the buffer. // Move bytes from the end to the beginning of the buffer.
std.mem.copyForwards(u8, buffer[0..(decodedValue.len)], buffer[(buffer.len - decodedValue.len)..]); std.mem.copyForwards(u8, buffer[0..(decodedValue.len)], buffer[(buffer.len - decodedValue.len)..]);
// Resize the buffer to free remaining bytes. // Resize the buffer to free remaining bytes.
_ = self.allocator.resize(buffer, decodedValue.len); if (self.allocator.resize(buffer, decodedValue.len))
buffer = buffer[0..decodedValue.len]; { // The buffer could have been resized, change variable length.
buffer = buffer[0..decodedValue.len];
}
else
{ // Could not resize the buffer, allocate a new one and free the old one.
const originalBuffer = buffer;
defer self.allocator.free(originalBuffer);
buffer = try self.allocator.dupe(u8, originalBuffer[0..decodedValue.len]);
}
// Add value to params. // Add value to params.
try self.params.put(try self.allocator.dupe(u8, key), buffer); try self.params.put(try self.allocator.dupe(u8, key), buffer);
@ -219,17 +227,17 @@ pub const RouteNode = struct {
} }
/// Get request handler depending on the request method. /// Get request handler depending on the request method.
pub fn getMethodHandler(self: Self, requestMethod: zap.Method) ?router.RouteHandler pub fn getMethodHandler(self: Self, requestMethod: zap.http.Method) ?router.RouteHandler
{ {
if (self.handle) |handle| if (self.handle) |handle|
{ // A handle object is defined, getting the right handler from it. { // A handle object is defined, getting the right handler from it.
return switch (requestMethod) return switch (requestMethod)
{ // Return the defined request handler from the request method. { // Return the defined request handler from the request method.
zap.Method.GET => handle.get orelse handle.any, zap.http.Method.GET => handle.get orelse handle.any,
zap.Method.POST => handle.post orelse handle.any, zap.http.Method.POST => handle.post orelse handle.any,
zap.Method.PATCH => handle.patch orelse handle.any, zap.http.Method.PATCH => handle.patch orelse handle.any,
zap.Method.PUT => handle.put orelse handle.any, zap.http.Method.PUT => handle.put orelse handle.any,
zap.Method.DELETE => handle.delete orelse handle.any, zap.http.Method.DELETE => handle.delete orelse handle.any,
else => handle.any, else => handle.any,
}; };
} }
@ -272,7 +280,7 @@ pub const RouteNode = struct {
/// Try to find a matching handler in the current route for the given path. /// Try to find a matching handler in the current route for the given path.
/// Return true when a route is matching the request correctly. /// Return true when a route is matching the request correctly.
pub fn match(self: *Self, requestMethod: zap.Method, path: *std.mem.SplitIterator(u8, std.mem.DelimiterType.scalar), result: *RoutingResult) !bool pub fn match(self: *Self, requestMethod: zap.http.Method, path: *std.mem.SplitIterator(u8, std.mem.DelimiterType.scalar), result: *RoutingResult) !bool
{ {
// Add pre, post, error and not found handlers, if defined. // Add pre, post, error and not found handlers, if defined.
try self.addHandlers(result); try self.addHandlers(result);
@ -280,9 +288,9 @@ pub const RouteNode = struct {
if (path.next()) |nextPath| if (path.next()) |nextPath|
{ // Trying to follow the path by finding a matching children. { // Trying to follow the path by finding a matching children.
if (self.staticChildren.get(nextPath)) |child| if (self.staticChildren.get(nextPath)) |child|
{ // There is a matching static child, continue to match the path on it. { // There is a matching static child, continue to match the path on it.
return try child.match(requestMethod, path, result); return try child.match(requestMethod, path, result);
} }
const currentIndex = path.index; const currentIndex = path.index;
// No matching static child, trying dynamic children. // No matching static child, trying dynamic children.

View file

@ -99,7 +99,7 @@ pub const Router = struct {
var errorHandlersIterator = std.mem.reverseIterator(routingResult.errorHandlers.items); var errorHandlersIterator = std.mem.reverseIterator(routingResult.errorHandlers.items);
while (errorHandlersIterator.next()) |errorHandler| while (errorHandlersIterator.next()) |errorHandler|
{ // For each error handler, try to run it with the given error. { // For each error handler, try to run it with the given error.
errorHandler(.{ errorHandler(MatchedRoute{
.route = routingResult.route, .route = routingResult.route,
.params = routingResult.params, .params = routingResult.params,
}, request, err) catch { }, request, err) catch {
@ -121,12 +121,12 @@ pub const Router = struct {
self.root.handleError.?(.{}, request, err) catch {}; self.root.handleError.?(.{}, request, err) catch {};
return; return;
}; };
defer routingResult.deinit();
// Matching the requested route. Put the result in routingResult pointer. // Matching the requested route. Put the result in routingResult pointer.
_ = self.root.match(request.methodAsEnum(), &path, routingResult) catch |err| { _ = self.root.match(request.methodAsEnum(), &path, routingResult) catch |err| {
Self.handleError(request, err, routingResult); Self.handleError(request, err, routingResult);
return; return;
}; };
defer routingResult.deinit();
// Try to run matched route handling. // Try to run matched route handling.
Self.runMatchedRouteHandling(routingResult, request) Self.runMatchedRouteHandling(routingResult, request)
@ -138,7 +138,7 @@ pub const Router = struct {
fn runMatchedRouteHandling(routingResult: *routeManager.RoutingResult, request: zap.Request) !void fn runMatchedRouteHandling(routingResult: *routeManager.RoutingResult, request: zap.Request) !void
{ {
// Initialized route data passed to handlers from the routing result. // Initialized route data passed to handlers from the routing result.
const routeData = .{ const routeData = MatchedRoute{
.route = routingResult.route, .route = routingResult.route,
.params = routingResult.params, .params = routingResult.params,
}; };
@ -165,7 +165,7 @@ pub const Router = struct {
} }
/// The on_request function of the HTTP listener. /// The on_request function of the HTTP listener.
pub fn onRequest(request: zap.Request) void pub fn onRequest(request: zap.Request) anyerror!void
{ {
// Call handle of the current router instance. // Call handle of the current router instance.
routerInstance.handle(request); routerInstance.handle(request);
@ -182,7 +182,7 @@ fn impossible(_: MatchedRoute, _: zap.Request) !void
fn defaultNotFoundHandler(_: MatchedRoute, request: zap.Request) !void fn defaultNotFoundHandler(_: MatchedRoute, request: zap.Request) !void
{ {
try request.setContentType(zap.ContentType.TEXT); try request.setContentType(zap.ContentType.TEXT);
request.setStatus(zap.StatusCode.not_found); request.setStatus(zap.http.StatusCode.not_found);
try request.sendBody("404: Not Found"); try request.sendBody("404: Not Found");
} }
@ -190,6 +190,6 @@ fn defaultNotFoundHandler(_: MatchedRoute, request: zap.Request) !void
fn defaultErrorHandler(_: MatchedRoute, request: zap.Request, _: anyerror) !void fn defaultErrorHandler(_: MatchedRoute, request: zap.Request, _: anyerror) !void
{ {
try request.setContentType(zap.ContentType.TEXT); try request.setContentType(zap.ContentType.TEXT);
request.setStatus(zap.StatusCode.internal_server_error); request.setStatus(zap.http.StatusCode.internal_server_error);
try request.sendBody("500: Internal Server Error"); try request.sendBody("500: Internal Server Error");
} }

View file

@ -127,11 +127,10 @@ fn runHttp() !void {
var listener = zap.HttpListener.init(.{ var listener = zap.HttpListener.init(.{
.interface = "127.0.0.1", .interface = "127.0.0.1",
.port = 8112, .port = 8112,
.log = false, .log = true,
// Add zouter to the listener. // Add zouter to the listener.
.on_request = zouter.Router.onRequest, .on_request = zouter.Router.onRequest,
}); });
zap.enableDebugLog();
try listener.listen(); try listener.listen();
const notFoundThread = try makeRequestThread(allocator, std.http.Method.GET, "http://127.0.0.1:8112/notfound/query", &notFoundResponse); const notFoundThread = try makeRequestThread(allocator, std.http.Method.GET, "http://127.0.0.1:8112/notfound/query", &notFoundResponse);