Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add type checking to simple_router's handle_func #125

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/router.zig
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,41 @@ pub fn handle_func_unbound(self: *Self, path: []const u8, h: zap.HttpRequestFn)
pub fn handle_func(self: *Self, path: []const u8, instance: *anyopaque, handler: anytype) !void {
// TODO: assert type of instance has handler

// Introspection checks on handler type
comptime {
const hand_info = @typeInfo(@TypeOf(handler));

// Need to check:
// 1) handler is function pointer
const f = blk: {
if (hand_info == .Pointer) {
const inner = @typeInfo(hand_info.Pointer.child);
if (inner == .Fn) {
break :blk inner.Fn;
}
}
@compileError("Expected handler to be a function pointer. Found " ++
@typeName(@TypeOf(handler)));
};

// 2) snd arg is zap.Request
if (f.params.len != 2) {
@compileError("Expected handler to have two paramters");
}
const arg_type = f.params[1].type.?;
if (arg_type != zap.Request) {
@compileError("Expected handler's second argument to be of type zap.Request. Found " ++
@typeName(arg_type));
}

// 3) handler returns void
const ret_info = @typeInfo(f.return_type.?);
if (ret_info != .Void) {
@compileError("Expected handler's return type to be void. Found " ++
@typeName(f.return_type.?));
}
}

if (path.len == 0) {
return RouterError.EmptyPath;
}
Expand Down
Loading