2022-11-27 06:56:16 +00:00
|
|
|
/// Middlewares are types with a method of type:
|
|
|
|
/// fn handle(
|
|
|
|
/// self: @This(),
|
|
|
|
/// request: *http.Request(< some type >),
|
|
|
|
/// response: *http.Response(< some type >),
|
|
|
|
/// context: anytype,
|
|
|
|
/// next_handler: anytype,
|
|
|
|
/// ) !void
|
|
|
|
///
|
|
|
|
/// If a middleware returns error.RouteMismatch, then it is assumed that the handler
|
|
|
|
/// did not apply to the request, and this is used by routing implementations to
|
|
|
|
/// determine when to stop attempting to match a route.
|
|
|
|
///
|
|
|
|
/// Terminal middlewares that are not implemented using other middlewares should
|
|
|
|
/// only accept a `void` value for `next_handler`.
|
2022-11-24 04:51:30 +00:00
|
|
|
const std = @import("std");
|
|
|
|
const http = @import("./lib.zig");
|
|
|
|
const util = @import("util");
|
2022-11-26 01:43:16 +00:00
|
|
|
const query_utils = @import("./query.zig");
|
|
|
|
const json_utils = @import("./json.zig");
|
2022-11-27 06:56:16 +00:00
|
|
|
|
|
|
|
/// Takes an iterable of middlewares and chains them together.
|
|
|
|
pub fn apply(middlewares: anytype) Apply(@TypeOf(middlewares)) {
|
|
|
|
return applyInternal(middlewares, std.meta.fields(@TypeOf(middlewares)));
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Helper function for the return type of `apply()`
|
|
|
|
pub fn Apply(comptime Middlewares: type) type {
|
|
|
|
return ApplyInternal(std.meta.fields(Middlewares));
|
|
|
|
}
|
|
|
|
|
|
|
|
fn ApplyInternal(comptime fields: []const std.builtin.Type.StructField) type {
|
|
|
|
if (fields.len == 0) return void;
|
|
|
|
|
|
|
|
return HandlerList(
|
|
|
|
fields[0].field_type,
|
|
|
|
ApplyInternal(fields[1..]),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn applyInternal(middlewares: anytype, comptime fields: []const std.builtin.Type.StructField) ApplyInternal(fields) {
|
|
|
|
if (fields.len == 0) return {};
|
|
|
|
return .{
|
|
|
|
.first = @field(middlewares, fields[0].name),
|
|
|
|
.next = applyInternal(middlewares, fields[1..]),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn HandlerList(comptime First: type, comptime Next: type) type {
|
|
|
|
return struct {
|
|
|
|
first: First,
|
|
|
|
next: Next,
|
|
|
|
|
|
|
|
pub fn handle(
|
|
|
|
self: @This(),
|
|
|
|
req: anytype,
|
|
|
|
res: anytype,
|
|
|
|
ctx: anytype,
|
|
|
|
next: void,
|
|
|
|
) !void {
|
|
|
|
_ = next;
|
|
|
|
return self.first.handle(req, res, ctx, self.next);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
test "apply" {
|
|
|
|
var count: usize = 0;
|
|
|
|
const NoOp = struct {
|
|
|
|
ptr: *usize,
|
|
|
|
fn handle(self: @This(), req: anytype, res: anytype, ctx: anytype, next: anytype) !void {
|
|
|
|
self.ptr.* += 1;
|
|
|
|
if (@TypeOf(next) != void) return next.handle(req, res, ctx, {});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const middlewares = .{
|
|
|
|
NoOp{ .ptr = &count },
|
|
|
|
NoOp{ .ptr = &count },
|
|
|
|
NoOp{ .ptr = &count },
|
|
|
|
NoOp{ .ptr = &count },
|
|
|
|
};
|
|
|
|
try std.testing.expectEqual(
|
|
|
|
Apply(@TypeOf(middlewares)),
|
|
|
|
HandlerList(NoOp, HandlerList(NoOp, HandlerList(NoOp, HandlerList(NoOp, void)))),
|
|
|
|
);
|
|
|
|
|
|
|
|
try apply(middlewares).handle(.{}, .{}, .{}, {});
|
|
|
|
try std.testing.expectEqual(count, 4);
|
|
|
|
}
|
|
|
|
|
|
|
|
test "injectContextValue - chained" {
|
|
|
|
try apply(.{
|
|
|
|
injectContextValue("abcd", @as(usize, 5)),
|
|
|
|
injectContextValue("efgh", @as(usize, 10)),
|
|
|
|
injectContextValue("ijkl", @as(usize, 15)),
|
|
|
|
ExpectContext(.{ .abcd = 5, .efgh = 10, .ijkl = 15 }){},
|
|
|
|
}).handle(.{}, .{}, .{}, {});
|
|
|
|
}
|
|
|
|
|
2022-11-27 01:33:46 +00:00
|
|
|
fn AddUniqueField(comptime Lhs: type, comptime N: usize, comptime name: [N]u8, comptime Val: type) type {
|
|
|
|
const Ctx = @Type(.{ .Struct = .{
|
|
|
|
.layout = .Auto,
|
|
|
|
.fields = std.meta.fields(Lhs) ++ &[_]std.builtin.Type.StructField{
|
|
|
|
.{
|
|
|
|
.name = &name,
|
|
|
|
.field_type = Val,
|
|
|
|
.alignment = if (@sizeOf(Val) != 0) @alignOf(Val) else 0,
|
|
|
|
.default_value = null,
|
|
|
|
.is_comptime = false,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
.decls = &.{},
|
|
|
|
.is_tuple = false,
|
|
|
|
} });
|
|
|
|
return Ctx;
|
|
|
|
}
|
|
|
|
|
|
|
|
fn AddField(comptime Lhs: type, comptime name: []const u8, comptime Val: type) type {
|
|
|
|
return AddUniqueField(Lhs, name.len, name[0..].*, Val);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn addField(lhs: anytype, comptime name: []const u8, val: anytype) AddField(@TypeOf(lhs), name, @TypeOf(val)) {
|
|
|
|
var result: AddField(@TypeOf(lhs), name, @TypeOf(val)) = undefined;
|
|
|
|
inline for (std.meta.fields(@TypeOf(lhs))) |f| @field(result, f.name) = @field(lhs, f.name);
|
|
|
|
@field(result, name) = val;
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
test "addField" {
|
|
|
|
const expect = std.testing.expect;
|
|
|
|
const eql = std.meta.eql;
|
2022-11-24 04:51:30 +00:00
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
try expect(eql(addField(.{}, "abcd", 5), .{ .abcd = 5 }));
|
|
|
|
try expect(eql(addField(.{ .abcd = 5 }, "efgh", 10), .{ .abcd = 5, .efgh = 10 }));
|
|
|
|
try expect(eql(
|
|
|
|
addField(addField(.{}, "abcd", 5), "efgh", 10),
|
|
|
|
.{ .abcd = 5, .efgh = 10 },
|
|
|
|
));
|
2022-11-24 11:30:49 +00:00
|
|
|
}
|
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
/// Adds a single value to the context object
|
2022-11-27 01:33:46 +00:00
|
|
|
pub fn InjectContextValue(comptime name: []const u8, comptime V: type) type {
|
|
|
|
return struct {
|
|
|
|
val: V,
|
|
|
|
pub fn handle(self: @This(), req: anytype, res: anytype, ctx: anytype, next: anytype) !void {
|
|
|
|
return next.handle(req, res, addField(ctx, name, self.val), {});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2022-11-24 11:30:49 +00:00
|
|
|
|
2022-11-27 01:33:46 +00:00
|
|
|
pub fn injectContextValue(comptime name: []const u8, val: anytype) InjectContextValue(name, @TypeOf(val)) {
|
|
|
|
return .{ .val = val };
|
|
|
|
}
|
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
test "InjectContextValue" {
|
|
|
|
try injectContextValue("abcd", @as(usize, 5))
|
|
|
|
.handle(.{}, .{}, .{}, ExpectContext(.{ .abcd = 5 }){});
|
|
|
|
try injectContextValue("abcd", @as(usize, 5))
|
|
|
|
.handle(.{}, .{}, .{ .efgh = @as(usize, 10) }, ExpectContext(.{ .abcd = 5, .efgh = 10 }){});
|
|
|
|
}
|
2022-11-24 04:51:30 +00:00
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
fn expectDeepEquals(expected: anytype, actual: anytype) !void {
|
|
|
|
const E = @TypeOf(expected);
|
|
|
|
const A = @TypeOf(actual);
|
|
|
|
if (E == void) return std.testing.expect(A == void);
|
|
|
|
try std.testing.expect(std.meta.fields(E).len == std.meta.fields(A).len);
|
|
|
|
inline for (std.meta.fields(E)) |f| {
|
|
|
|
const e = @field(expected, f.name);
|
|
|
|
const a = @field(actual, f.name);
|
|
|
|
if (comptime std.meta.trait.isZigString(f.field_type)) {
|
|
|
|
try std.testing.expectEqualStrings(a, e);
|
|
|
|
} else {
|
|
|
|
try std.testing.expectEqual(a, e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Helper for testing purposes
|
|
|
|
fn ExpectContext(comptime val: anytype) type {
|
|
|
|
return struct {
|
|
|
|
pub fn handle(_: @This(), _: anytype, _: anytype, ctx: anytype, _: void) !void {
|
|
|
|
try expectDeepEquals(val, ctx);
|
2022-11-24 04:51:30 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2022-11-27 06:56:16 +00:00
|
|
|
fn expectContext(comptime val: anytype) ExpectContext(val) {
|
|
|
|
return .{};
|
|
|
|
}
|
2022-11-24 04:51:30 +00:00
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
/// Catches any errors returned by the `next` chain, and passes them via context
|
|
|
|
/// to an error handler if one occurs
|
2022-11-24 04:51:30 +00:00
|
|
|
pub fn CatchErrors(comptime ErrorHandler: type) type {
|
|
|
|
return struct {
|
|
|
|
error_handler: ErrorHandler,
|
|
|
|
pub fn handle(self: @This(), req: anytype, res: anytype, ctx: anytype, next: anytype) !void {
|
|
|
|
return next.handle(req, res, ctx, {}) catch |err| {
|
|
|
|
return self.error_handler.handle(
|
|
|
|
req,
|
|
|
|
res,
|
2022-11-27 01:52:30 +00:00
|
|
|
addField(ctx, "err", err),
|
2022-11-24 04:51:30 +00:00
|
|
|
next,
|
|
|
|
);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2022-11-27 06:56:16 +00:00
|
|
|
|
2022-11-24 04:51:30 +00:00
|
|
|
pub fn catchErrors(error_handler: anytype) CatchErrors(@TypeOf(error_handler)) {
|
|
|
|
return .{ .error_handler = error_handler };
|
|
|
|
}
|
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
/// Default error handler for CatchErrors, logs the error and outputs responds with a 500 if
|
|
|
|
/// a response has not been written yet
|
2022-11-24 04:51:30 +00:00
|
|
|
pub const default_error_handler = struct {
|
2022-11-27 06:56:16 +00:00
|
|
|
fn handle(_: @This(), req: anytype, res: anytype, ctx: anytype, _: anytype) !void {
|
|
|
|
const should_log = !@import("builtin").is_test;
|
|
|
|
if (should_log) std.log.err("Error {} on uri {s}", .{ ctx.err, req.uri });
|
2022-11-24 04:51:30 +00:00
|
|
|
|
|
|
|
// Tell the server to close the connection after this request
|
|
|
|
res.should_close = true;
|
2022-11-26 01:43:16 +00:00
|
|
|
|
|
|
|
var buf: [1024]u8 = undefined;
|
|
|
|
var fba = std.heap.FixedBufferAllocator.init(&buf);
|
|
|
|
var headers = http.Fields.init(fba.allocator());
|
|
|
|
if (!res.was_opened) {
|
|
|
|
var stream = res.open(.internal_server_error, &headers) catch return;
|
|
|
|
defer stream.close();
|
|
|
|
stream.finish() catch {};
|
|
|
|
}
|
2022-11-24 04:51:30 +00:00
|
|
|
}
|
|
|
|
}{};
|
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
test "CatchErrors" {
|
|
|
|
const TestResponse = struct {
|
|
|
|
should_close: bool = false,
|
|
|
|
was_opened: bool = false,
|
|
|
|
|
|
|
|
test_should_open: bool,
|
|
|
|
const TestStream = struct {
|
|
|
|
fn close(_: *@This()) void {}
|
|
|
|
fn finish(_: *@This()) !void {}
|
|
|
|
};
|
|
|
|
|
|
|
|
fn open(self: *@This(), status: http.Status, _: *http.Fields) !TestStream {
|
|
|
|
self.was_opened = true;
|
|
|
|
if (!self.test_should_open) return error.ResponseOpenedTwice;
|
|
|
|
try std.testing.expectEqual(status, .internal_server_error);
|
|
|
|
return .{};
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const middleware_list = apply(.{
|
|
|
|
catchErrors(default_error_handler),
|
|
|
|
struct {
|
|
|
|
fn handle(_: @This(), _: anytype, _: anytype, _: anytype, _: anytype) !void {
|
|
|
|
return error.SomeError;
|
|
|
|
}
|
|
|
|
}{},
|
|
|
|
});
|
|
|
|
|
|
|
|
var response = TestResponse{ .test_should_open = true };
|
|
|
|
try middleware_list.handle(.{ .uri = "abcd" }, &response, .{}, {});
|
|
|
|
try std.testing.expect(response.should_close);
|
|
|
|
|
|
|
|
// Test that it doesn't open a response if one was already opened
|
|
|
|
response = TestResponse{ .test_should_open = false, .was_opened = true };
|
|
|
|
try middleware_list.handle(.{ .uri = "abcd" }, &response, .{}, {});
|
|
|
|
try std.testing.expect(response.should_close);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Takes the request uri provided and splits it into "path", "query_string", and "fragment_string"
|
|
|
|
/// parts, which are placed into context.
|
|
|
|
const SplitUri = struct {
|
2022-11-24 04:51:30 +00:00
|
|
|
pub fn handle(_: @This(), req: anytype, res: anytype, ctx: anytype, next: anytype) !void {
|
|
|
|
var frag_split = std.mem.split(u8, req.uri, "#");
|
|
|
|
const without_fragment = frag_split.first();
|
|
|
|
const fragment = frag_split.rest();
|
|
|
|
|
|
|
|
var query_split = std.mem.split(u8, without_fragment, "?");
|
|
|
|
const path = query_split.first();
|
|
|
|
const query = query_split.rest();
|
|
|
|
|
2022-11-27 01:52:30 +00:00
|
|
|
const new_ctx = addField(
|
|
|
|
addField(
|
|
|
|
addField(ctx, "path", path),
|
|
|
|
"query_string",
|
|
|
|
query,
|
|
|
|
),
|
|
|
|
"fragment_string",
|
|
|
|
fragment,
|
|
|
|
);
|
2022-11-24 04:51:30 +00:00
|
|
|
|
|
|
|
return next.handle(
|
|
|
|
req,
|
|
|
|
res,
|
2022-11-27 01:52:30 +00:00
|
|
|
new_ctx,
|
2022-11-24 04:51:30 +00:00
|
|
|
{},
|
|
|
|
);
|
|
|
|
}
|
2022-11-27 06:56:16 +00:00
|
|
|
};
|
|
|
|
pub const split_uri = SplitUri{};
|
|
|
|
|
|
|
|
test "split_uri" {
|
|
|
|
const testCase = struct {
|
|
|
|
fn func(uri: []const u8, ctx: anytype, expected: anytype) !void {
|
|
|
|
const v = apply(.{
|
|
|
|
split_uri,
|
|
|
|
expectContext(expected),
|
|
|
|
});
|
|
|
|
try v.handle(.{ .uri = uri }, .{}, ctx, {});
|
|
|
|
}
|
|
|
|
}.func;
|
|
|
|
|
|
|
|
try testCase("/", .{}, .{ .path = "/", .query_string = "", .fragment_string = "" });
|
|
|
|
try testCase("", .{}, .{ .path = "", .query_string = "", .fragment_string = "" });
|
|
|
|
try testCase("/path", .{}, .{ .path = "/path", .query_string = "", .fragment_string = "" });
|
|
|
|
try testCase("?abcd=1234", .{}, .{ .path = "", .query_string = "abcd=1234", .fragment_string = "" });
|
|
|
|
try testCase("#abcd", .{}, .{ .path = "", .query_string = "", .fragment_string = "abcd" });
|
|
|
|
try testCase("/abcd/efgh?query=no#frag", .{}, .{ .path = "/abcd/efgh", .query_string = "query=no", .fragment_string = "frag" });
|
|
|
|
}
|
2022-11-24 04:51:30 +00:00
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
/// Routes a request between the provided routes.
|
|
|
|
///
|
|
|
|
/// CURRENTLY: Does not do this intelligently, all routing is handled by the routes themselves.
|
|
|
|
/// TODO: Consider implementing this with a hashmap?
|
2022-11-26 01:43:16 +00:00
|
|
|
pub fn Router(comptime Routes: type) type {
|
2022-11-24 11:30:49 +00:00
|
|
|
return struct {
|
2022-11-26 01:43:16 +00:00
|
|
|
routes: Routes,
|
2022-11-24 04:51:30 +00:00
|
|
|
|
2022-11-24 11:30:49 +00:00
|
|
|
pub fn handle(self: @This(), req: anytype, res: anytype, ctx: anytype, next: void) !void {
|
|
|
|
_ = next;
|
|
|
|
|
|
|
|
inline for (self.routes) |r| {
|
|
|
|
if (r.handle(req, res, ctx, {})) |_|
|
|
|
|
// success
|
|
|
|
return
|
|
|
|
else |err| switch (err) {
|
|
|
|
error.RouteMismatch => {},
|
|
|
|
else => return err,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return error.RouteMismatch;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2022-11-26 01:43:16 +00:00
|
|
|
pub fn router(routes: anytype) Router(@TypeOf(routes)) {
|
|
|
|
return Router(@TypeOf(routes)){ .routes = routes };
|
2022-11-24 11:55:47 +00:00
|
|
|
}
|
2022-11-24 11:30:49 +00:00
|
|
|
|
|
|
|
// helper function for doing route analysis
|
|
|
|
fn pathMatches(route: []const u8, path: []const u8) bool {
|
|
|
|
var path_iter = util.PathIter.from(path);
|
|
|
|
var route_iter = util.PathIter.from(route);
|
|
|
|
while (route_iter.next()) |route_segment| {
|
2022-11-24 04:51:30 +00:00
|
|
|
const path_segment = path_iter.next() orelse return false;
|
|
|
|
if (route_segment.len > 0 and route_segment[0] == ':') {
|
|
|
|
// Route Argument
|
2022-11-27 07:14:19 +00:00
|
|
|
if (path_segment.len == 0) return false;
|
2022-11-24 04:51:30 +00:00
|
|
|
} else {
|
|
|
|
if (!std.ascii.eqlIgnoreCase(route_segment, path_segment)) return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (path_iter.next() != null) return false;
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
2022-11-27 06:56:16 +00:00
|
|
|
|
|
|
|
/// Handler that either calls its next middleware parameter or returns error.RouteMismatch
|
|
|
|
/// depending on if the request matches the described route.
|
|
|
|
/// Must be below `split_uri` on the middleware list.
|
|
|
|
///
|
|
|
|
/// Format:
|
|
|
|
/// Each route segment can be either a literal string or an argument. Literal strings
|
|
|
|
/// must match exactly in order to constitute a matching route. Arguments must begin with
|
|
|
|
/// the character ':', with the remainer of the segment referring to the name of the argument.
|
|
|
|
/// Argument values must be nonempty.
|
|
|
|
///
|
|
|
|
/// For example, the route "/abc/:foo/def" would match "/abc/x/def" or "/abc/blahblah/def" but
|
|
|
|
/// not "/abc//def".
|
2022-11-24 11:30:49 +00:00
|
|
|
pub const Route = struct {
|
|
|
|
pub const Desc = struct {
|
|
|
|
path: []const u8,
|
|
|
|
method: http.Method,
|
|
|
|
};
|
2022-11-24 04:51:30 +00:00
|
|
|
|
2022-11-24 11:30:49 +00:00
|
|
|
desc: Desc,
|
2022-11-24 04:51:30 +00:00
|
|
|
|
2022-11-24 11:30:49 +00:00
|
|
|
fn applies(self: @This(), req: anytype, ctx: anytype) bool {
|
|
|
|
if (self.desc.method != req.method) return false;
|
2022-11-24 04:51:30 +00:00
|
|
|
|
2022-11-26 01:43:16 +00:00
|
|
|
const eff_path = if (@hasField(@TypeOf(ctx), "path"))
|
2022-11-24 11:30:49 +00:00
|
|
|
ctx.path
|
|
|
|
else
|
|
|
|
std.mem.sliceTo(req.uri, '?');
|
2022-11-24 04:51:30 +00:00
|
|
|
|
2022-11-24 11:30:49 +00:00
|
|
|
return pathMatches(self.desc.path, eff_path);
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn handle(self: @This(), req: anytype, res: anytype, ctx: anytype, next: anytype) !void {
|
|
|
|
return if (self.applies(req, ctx))
|
|
|
|
next.handle(req, res, ctx, {})
|
|
|
|
else
|
|
|
|
error.RouteMismatch;
|
|
|
|
}
|
|
|
|
};
|
2022-11-24 04:51:30 +00:00
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
test "route" {
|
|
|
|
const testCase = struct {
|
|
|
|
fn func(should_match: bool, route: Route.Desc, method: http.Method, path: []const u8) !void {
|
|
|
|
const no_op = struct {
|
|
|
|
fn handle(_: anytype, _: anytype, _: anytype, _: anytype, _: anytype) !void {}
|
|
|
|
}{};
|
|
|
|
const result = (Route{ .desc = route }).handle(.{ .method = method }, .{}, .{ .path = path }, no_op);
|
|
|
|
try if (should_match) result else std.testing.expectError(error.RouteMismatch, result);
|
|
|
|
}
|
|
|
|
}.func;
|
|
|
|
|
|
|
|
try testCase(true, .{ .method = .GET, .path = "/" }, .GET, "/");
|
|
|
|
try testCase(true, .{ .method = .GET, .path = "/" }, .GET, "");
|
|
|
|
try testCase(true, .{ .method = .GET, .path = "/abcd" }, .GET, "/abcd");
|
|
|
|
try testCase(true, .{ .method = .GET, .path = "/abcd" }, .GET, "abcd");
|
|
|
|
try testCase(true, .{ .method = .POST, .path = "/" }, .POST, "/");
|
|
|
|
try testCase(true, .{ .method = .POST, .path = "/" }, .POST, "");
|
|
|
|
try testCase(true, .{ .method = .POST, .path = "/abcd" }, .POST, "/abcd");
|
|
|
|
try testCase(true, .{ .method = .POST, .path = "/abcd" }, .POST, "abcd");
|
|
|
|
try testCase(true, .{ .method = .POST, .path = "/abcd/efgh" }, .POST, "abcd/efgh");
|
|
|
|
try testCase(true, .{ .method = .GET, .path = "/abcd/:arg" }, .GET, "abcd/efgh");
|
|
|
|
try testCase(true, .{ .method = .GET, .path = "/abcd/:arg/xyz" }, .GET, "abcd/efgh/xyz");
|
|
|
|
|
|
|
|
try testCase(false, .{ .method = .POST, .path = "/" }, .GET, "/");
|
|
|
|
try testCase(false, .{ .method = .GET, .path = "/abcd" }, .GET, "");
|
|
|
|
try testCase(false, .{ .method = .GET, .path = "/" }, .GET, "/abcd");
|
|
|
|
try testCase(false, .{ .method = .POST, .path = "/abcd/efgh" }, .POST, "efgh");
|
|
|
|
try testCase(false, .{ .method = .GET, .path = "/abcd/:arg" }, .GET, "/abcd/");
|
|
|
|
try testCase(false, .{ .method = .GET, .path = "/abcd/:arg/xyz" }, .GET, "abcd/efgh/");
|
|
|
|
try testCase(false, .{ .method = .GET, .path = "/abcd/:arg/xyz" }, .GET, "abcd/efgh/xyz/foo");
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Mounts a router subtree under a given path. Middlewares further down on the list
|
|
|
|
/// are called with the path prefix specified by `route` removed from the path.
|
|
|
|
/// Must be below `split_uri` on the middleware list.
|
2022-11-24 04:51:30 +00:00
|
|
|
pub fn Mount(comptime route: []const u8) type {
|
|
|
|
return struct {
|
|
|
|
pub fn handle(_: @This(), req: anytype, res: anytype, ctx: anytype, next: anytype) !void {
|
|
|
|
var path_iter = util.PathIter.from(ctx.path);
|
|
|
|
comptime var route_iter = util.PathIter.from(route);
|
2022-11-27 06:56:16 +00:00
|
|
|
var path_unused: []const u8 = ctx.path;
|
2022-11-24 04:51:30 +00:00
|
|
|
|
|
|
|
inline while (comptime route_iter.next()) |route_segment| {
|
|
|
|
if (comptime route_segment.len == 0) continue;
|
|
|
|
const path_segment = path_iter.next() orelse return error.RouteMismatch;
|
|
|
|
path_unused = path_iter.rest();
|
|
|
|
if (comptime route_segment[0] == ':') {
|
|
|
|
@compileLog("Argument segments cannot be mounted");
|
|
|
|
// Route Argument
|
|
|
|
} else {
|
|
|
|
if (!std.ascii.eqlIgnoreCase(route_segment, path_segment)) return error.RouteMismatch;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var new_ctx = ctx;
|
|
|
|
new_ctx.path = path_unused;
|
|
|
|
return next.handle(req, res, new_ctx, {});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
pub fn mount(comptime route: []const u8) Mount(route) {
|
|
|
|
return .{};
|
|
|
|
}
|
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
test "mount" {
|
|
|
|
const testCase = struct {
|
|
|
|
fn func(comptime base: []const u8, request: []const u8, comptime expected: ?[]const u8) !void {
|
|
|
|
const result = mount(base).handle(.{}, .{}, addField(.{}, "path", request), expectContext(.{ .path = expected orelse "" }));
|
|
|
|
try if (expected != null) result else std.testing.expectError(error.RouteMismatch, result);
|
2022-11-24 04:51:30 +00:00
|
|
|
}
|
2022-11-27 06:56:16 +00:00
|
|
|
}.func;
|
|
|
|
try testCase("/api/", "/api/", "");
|
|
|
|
try testCase("/api/", "/api/abcd", "abcd");
|
|
|
|
try testCase("/api/", "/api/abcd/efgh", "abcd/efgh");
|
|
|
|
try testCase("/api/", "/api/abcd/efgh/", "abcd/efgh/");
|
|
|
|
try testCase("/api/v0", "/api/v0/call", "call");
|
|
|
|
|
|
|
|
try testCase("/api/", "/web/abcd/efgh/", null);
|
|
|
|
try testCase("/api/", "/", null);
|
|
|
|
try testCase("/api/", "/ap", null);
|
|
|
|
try testCase("/api/v0", "/api/v1/", null);
|
2022-11-24 04:51:30 +00:00
|
|
|
}
|
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
fn parseArgsFromPath(comptime route: []const u8, comptime Args: type, path: []const u8) !Args {
|
2022-11-24 04:51:30 +00:00
|
|
|
var args: Args = undefined;
|
|
|
|
var path_iter = util.PathIter.from(path);
|
|
|
|
comptime var route_iter = util.PathIter.from(route);
|
|
|
|
inline while (comptime route_iter.next()) |route_segment| {
|
|
|
|
const path_segment = path_iter.next() orelse return error.RouteMismatch;
|
|
|
|
if (route_segment.len > 0 and route_segment[0] == ':') {
|
|
|
|
// route segment is an argument segment
|
2022-11-27 06:56:16 +00:00
|
|
|
if (path_segment.len == 0) return error.RouteMismatch;
|
2022-11-24 04:51:30 +00:00
|
|
|
const A = @TypeOf(@field(args, route_segment[1..]));
|
2022-11-27 06:56:16 +00:00
|
|
|
@field(args, route_segment[1..]) = try parseArgFromPath(A, path_segment);
|
2022-11-24 04:51:30 +00:00
|
|
|
} else {
|
|
|
|
if (!std.ascii.eqlIgnoreCase(route_segment, path_segment)) return error.RouteMismatch;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (path_iter.next() != null) return error.RouteMismatch;
|
|
|
|
|
|
|
|
return args;
|
|
|
|
}
|
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
fn parseArgFromPath(comptime T: type, segment: []const u8) !T {
|
2022-11-24 04:51:30 +00:00
|
|
|
if (T == []const u8) return segment;
|
|
|
|
if (comptime std.meta.trait.isContainer(T) and std.meta.trait.hasFn("parse")(T)) return T.parse(segment);
|
2022-11-27 06:56:16 +00:00
|
|
|
if (comptime std.meta.trait.is(.Int)(T)) return std.fmt.parseInt(T, segment, 0);
|
2022-11-24 04:51:30 +00:00
|
|
|
|
|
|
|
@compileError("Unsupported Type " ++ @typeName(T));
|
|
|
|
}
|
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
/// Parse arguments directly the request path.
|
|
|
|
/// Must be placed after a `split_uri` middleware in order to get `path` from context.
|
|
|
|
///
|
|
|
|
/// Route arguments are specified in the same format as for Route. The name of the argument
|
|
|
|
/// refers to the field name in Args that the argument will be parsed to.
|
|
|
|
///
|
|
|
|
/// This currently works with arguments of 3 different types:
|
|
|
|
/// - integers
|
|
|
|
/// - []const u8,
|
|
|
|
/// - anything with a function of the form:
|
|
|
|
/// * T.parse([]const u8) Error!T
|
|
|
|
/// * This function cannot hold a reference to the passed string once it appears
|
|
|
|
///
|
|
|
|
/// Example:
|
|
|
|
/// ParsePathArgs("/:id/foo/:name/byrank/:rank", struct {
|
|
|
|
/// id: util.Uuid,
|
|
|
|
/// name: []const u8,
|
|
|
|
/// rank: u32,
|
|
|
|
/// })
|
|
|
|
/// Would parse a path of "/00000000-0000-0000-0000-000000000000/foo/jaina/byrank/3" into
|
|
|
|
/// .{ .id = try Uuid.parse("00000000-0000-0000-0000-000000000000"), .name = "jaina", .rank = 3 }
|
2022-11-24 04:51:30 +00:00
|
|
|
pub fn ParsePathArgs(comptime route: []const u8, comptime Args: type) type {
|
|
|
|
return struct {
|
|
|
|
pub fn handle(_: @This(), req: anytype, res: anytype, ctx: anytype, next: anytype) !void {
|
2022-11-27 01:33:46 +00:00
|
|
|
if (Args == void) return next.handle(req, res, addField(ctx, "args", {}), {});
|
2022-11-24 04:51:30 +00:00
|
|
|
return next.handle(
|
|
|
|
req,
|
|
|
|
res,
|
2022-11-27 06:56:16 +00:00
|
|
|
addField(ctx, "args", try parseArgsFromPath(route, Args, ctx.path)),
|
2022-11-24 04:51:30 +00:00
|
|
|
{},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2022-11-27 06:56:16 +00:00
|
|
|
pub fn parsePathArgs(comptime route: []const u8, comptime Args: type) ParsePathArgs(route, Args) {
|
|
|
|
return .{};
|
|
|
|
}
|
|
|
|
|
|
|
|
test "ParsePathArgs" {
|
|
|
|
const testCase = struct {
|
|
|
|
fn func(comptime route: []const u8, comptime Args: type, path: []const u8, expected: anytype) !void {
|
|
|
|
const check = struct {
|
|
|
|
expected: @TypeOf(expected),
|
|
|
|
path: []const u8,
|
|
|
|
fn handle(self: @This(), _: anytype, _: anytype, ctx: anytype, _: void) !void {
|
|
|
|
try expectDeepEquals(self.expected, ctx.args);
|
|
|
|
try std.testing.expectEqualStrings(self.path, ctx.path);
|
|
|
|
}
|
|
|
|
}{ .expected = expected, .path = path };
|
|
|
|
try parsePathArgs(route, Args).handle(.{}, .{}, .{ .path = path }, check);
|
|
|
|
}
|
|
|
|
}.func;
|
|
|
|
|
|
|
|
try testCase("/", void, "/", {});
|
|
|
|
try testCase("/:id", struct { id: usize }, "/3", .{ .id = 3 });
|
|
|
|
try testCase("/:str", struct { str: []const u8 }, "/abcd", .{ .str = "abcd" });
|
|
|
|
try testCase("/:id/xyz/:str", struct { id: usize, str: []const u8 }, "/3/xyz/abcd", .{ .id = 3, .str = "abcd" });
|
|
|
|
try testCase("/:id", struct { id: util.Uuid }, "/" ++ util.Uuid.nil.toCharArray(), .{ .id = util.Uuid.nil });
|
|
|
|
|
|
|
|
try std.testing.expectError(error.RouteMismatch, testCase("/:id", struct { id: usize }, "/", .{}));
|
|
|
|
try std.testing.expectError(error.RouteMismatch, testCase("/abcd/:id", struct { id: usize }, "/123", .{}));
|
|
|
|
try std.testing.expectError(error.RouteMismatch, testCase("/:id", struct { id: usize }, "/3/id/blahblah", .{ .id = 3 }));
|
|
|
|
try std.testing.expectError(error.InvalidCharacter, testCase("/:id", struct { id: usize }, "/xyz", .{}));
|
|
|
|
}
|
2022-11-24 04:51:30 +00:00
|
|
|
|
|
|
|
const BaseContentType = enum {
|
|
|
|
json,
|
|
|
|
url_encoded,
|
|
|
|
octet_stream,
|
|
|
|
|
|
|
|
other,
|
|
|
|
};
|
|
|
|
|
2022-11-27 10:21:22 +00:00
|
|
|
fn parseBodyFromRequest(comptime T: type, content_type: ?[]const u8, reader: anytype, alloc: std.mem.Allocator) !T {
|
|
|
|
// Use json by default for now for testing purposes
|
|
|
|
const parser_type = matchContentType(content_type) orelse .json;
|
2022-11-24 04:51:30 +00:00
|
|
|
const buf = try reader.readAllAlloc(alloc, 1 << 16);
|
|
|
|
defer alloc.free(buf);
|
|
|
|
|
2022-11-27 10:21:22 +00:00
|
|
|
switch (parser_type) {
|
2022-11-24 04:51:30 +00:00
|
|
|
.octet_stream, .json => {
|
|
|
|
const body = try json_utils.parse(T, buf, alloc);
|
|
|
|
defer json_utils.parseFree(body, alloc);
|
|
|
|
|
|
|
|
return try util.deepClone(alloc, body);
|
|
|
|
},
|
|
|
|
.url_encoded => return query_utils.parseQuery(alloc, T, buf) catch |err| switch (err) {
|
|
|
|
error.NoQuery => error.NoBody,
|
|
|
|
else => err,
|
|
|
|
},
|
|
|
|
else => return error.UnsupportedMediaType,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
// figure out what base parser to use
|
2022-11-24 04:51:30 +00:00
|
|
|
fn matchContentType(hdr: ?[]const u8) ?BaseContentType {
|
|
|
|
if (hdr) |h| {
|
|
|
|
if (std.ascii.eqlIgnoreCase(h, "application/x-www-form-urlencoded")) return .url_encoded;
|
|
|
|
if (std.ascii.eqlIgnoreCase(h, "application/json")) return .json;
|
|
|
|
if (std.ascii.eqlIgnoreCase(h, "application/octet-stream")) return .octet_stream;
|
|
|
|
|
|
|
|
return .other;
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
/// Parses a set of body arguments from the request body based on the request's Content-Type
|
|
|
|
/// header.
|
|
|
|
///
|
|
|
|
/// The exact method for parsing depends partially on the Content-Type. json types are preferred
|
|
|
|
/// TODO: Need tests for this, including various Content-Type values
|
2022-11-24 04:51:30 +00:00
|
|
|
pub fn ParseBody(comptime Body: type) type {
|
|
|
|
return struct {
|
|
|
|
pub fn handle(_: @This(), req: anytype, res: anytype, ctx: anytype, next: anytype) !void {
|
2022-11-27 01:33:46 +00:00
|
|
|
const content_type = req.headers.get("Content-Type");
|
|
|
|
if (Body == void) {
|
|
|
|
if (content_type != null) return error.UnexpectedBody;
|
|
|
|
const new_ctx = addField(ctx, "body", {});
|
|
|
|
//if (true) @compileError("bug");
|
|
|
|
return next.handle(req, res, new_ctx, {});
|
|
|
|
}
|
|
|
|
|
2022-11-24 04:51:30 +00:00
|
|
|
var stream = req.body orelse return error.NoBody;
|
2022-11-27 10:21:22 +00:00
|
|
|
const body = try parseBodyFromRequest(Body, content_type, stream.reader(), ctx.allocator);
|
2022-11-26 01:43:16 +00:00
|
|
|
defer util.deepFree(ctx.allocator, body);
|
2022-11-24 04:51:30 +00:00
|
|
|
|
2022-11-26 01:43:16 +00:00
|
|
|
return next.handle(
|
2022-11-24 04:51:30 +00:00
|
|
|
req,
|
|
|
|
res,
|
2022-11-27 01:33:46 +00:00
|
|
|
addField(ctx, "body", body),
|
2022-11-26 01:43:16 +00:00
|
|
|
{},
|
2022-11-24 04:51:30 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2022-11-27 06:56:16 +00:00
|
|
|
pub fn parseBody(comptime Body: type) ParseBody(Body) {
|
|
|
|
return .{};
|
|
|
|
}
|
2022-11-24 04:51:30 +00:00
|
|
|
|
2022-11-27 10:21:22 +00:00
|
|
|
test "parseBodyFromRequest" {
|
|
|
|
const testCase = struct {
|
|
|
|
fn case(content_type: []const u8, body: []const u8, expected: anytype) !void {
|
|
|
|
var stream = std.io.StreamSource{ .const_buffer = std.io.fixedBufferStream(body) };
|
|
|
|
const result = try parseBodyFromRequest(@TypeOf(expected), content_type, stream.reader(), std.testing.allocator);
|
|
|
|
defer util.deepFree(std.testing.allocator, result);
|
|
|
|
|
|
|
|
try util.testing.expectDeepEqual(expected, result);
|
|
|
|
}
|
|
|
|
}.case;
|
|
|
|
|
|
|
|
const Struct = struct {
|
|
|
|
id: usize,
|
|
|
|
};
|
|
|
|
try testCase("application/json", "{\"id\": 3}", Struct{ .id = 3 });
|
|
|
|
try testCase("application/x-www-form-urlencoded", "id=3", Struct{ .id = 3 });
|
|
|
|
}
|
|
|
|
|
|
|
|
test "parseBody" {
|
|
|
|
const Struct = struct {
|
|
|
|
foo: []const u8,
|
|
|
|
};
|
|
|
|
const body =
|
|
|
|
\\{"foo": "bar"}
|
|
|
|
;
|
|
|
|
var stream = std.io.StreamSource{ .const_buffer = std.io.fixedBufferStream(body) };
|
|
|
|
var headers = http.Fields.init(std.testing.allocator);
|
|
|
|
defer headers.deinit();
|
|
|
|
|
|
|
|
try parseBody(Struct).handle(
|
|
|
|
.{ .body = @as(?std.io.StreamSource, stream), .headers = headers },
|
|
|
|
.{},
|
|
|
|
.{ .allocator = std.testing.allocator },
|
|
|
|
struct {
|
|
|
|
fn handle(_: anytype, _: anytype, _: anytype, ctx: anytype, _: void) !void {
|
|
|
|
try util.testing.expectDeepEqual(Struct{ .foo = "bar" }, ctx.body);
|
|
|
|
}
|
|
|
|
}{},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-11-27 06:56:16 +00:00
|
|
|
/// Parses query parameters as defined in query.zig
|
2022-11-24 11:30:49 +00:00
|
|
|
pub fn ParseQueryParams(comptime QueryParams: type) type {
|
2022-11-24 04:51:30 +00:00
|
|
|
return struct {
|
2022-11-24 11:30:49 +00:00
|
|
|
pub fn handle(_: @This(), req: anytype, res: anytype, ctx: anytype, next: anytype) !void {
|
2022-11-27 01:33:46 +00:00
|
|
|
if (QueryParams == void) return next.handle(req, res, addField(ctx, "query_params", {}), {});
|
2022-11-24 04:51:30 +00:00
|
|
|
const query = try query_utils.parseQuery(ctx.allocator, QueryParams, ctx.query_string);
|
2022-11-26 01:43:16 +00:00
|
|
|
defer util.deepFree(ctx.allocator, query);
|
2022-11-24 04:51:30 +00:00
|
|
|
|
2022-11-24 11:30:49 +00:00
|
|
|
return next.handle(
|
2022-11-24 04:51:30 +00:00
|
|
|
req,
|
|
|
|
res,
|
2022-11-27 01:33:46 +00:00
|
|
|
addField(ctx, "query_params", query),
|
2022-11-24 11:30:49 +00:00
|
|
|
{},
|
2022-11-24 04:51:30 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|