-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathmiddleware.zig
More file actions
77 lines (67 loc) · 2.47 KB
/
Copy pathmiddleware.zig
File metadata and controls
77 lines (67 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const std = @import("std");
const Context = @import("server.zig").Context;
const Handler = @import("server.zig").Handler;
/// Returns a middleware that executes given steps as a chain. Every step should
/// either respond or call the next step in the chain.
pub fn chain(comptime steps: anytype) Handler {
const handlers = comptime brk: {
var res: [steps.len]*const Handler = undefined;
for (steps, 0..) |m, i| res[i] = &Context.wrap(m);
break :brk &res;
};
const H = struct {
fn handleChain(ctx: *Context) anyerror!void {
if (!try ctx.runScoped(handlers[0], handlers[1..])) {
return;
}
// TODO: tail-call?
return ctx.next();
}
};
return H.handleChain;
}
/// Returns a middleware that matches the request path prefix and calls the
/// given handler/middleware. If the prefix matches, the request path is
/// modified to remove the prefix. If the handler/middleware responds, the
/// chain is stopped.
pub fn group(comptime prefix: []const u8, handler: anytype) Handler {
const H = struct {
fn handleGroup(ctx: *Context) anyerror!void {
if (std.mem.startsWith(u8, ctx.req.url.path, prefix)) {
const orig = ctx.req.url.path;
ctx.req.url.path = ctx.req.url.path[prefix.len..];
defer ctx.req.url.path = orig;
if (!try ctx.runScoped(&Context.wrap(handler), &.{})) return;
}
// TODO: tail-call?
return ctx.next();
}
};
return H.handleGroup;
}
/// Returns a handler that sends the given, comptime response.
pub fn send(comptime res: anytype) Handler {
const H = struct {
fn handleSend(ctx: *Context) anyerror!void {
return ctx.res.send(res);
}
};
return H.handleSend;
}
/// Returns a middleware for logging all requests going through it.
pub fn logger(options: struct { scope: @TypeOf(.EnumLiteral) = .server }) Handler {
const log = std.log.scoped(options.scope);
const H = struct {
fn handleLogger(ctx: *Context) anyerror!void {
const start = std.time.milliTimestamp();
defer log.debug("{s} {s} {} [{}ms]", .{
@tagName(ctx.req.method),
ctx.req.raw.head.target,
@intFromEnum(ctx.res.status),
std.time.milliTimestamp() - start,
});
return ctx.next();
}
};
return H.handleLogger;
}