-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuiltin_middlewares.zig
More file actions
203 lines (183 loc) · 7.47 KB
/
builtin_middlewares.zig
File metadata and controls
203 lines (183 loc) · 7.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
const std = @import("std");
const zhttp = @import("zhttp");
const common = @import("common.zig");
const ReqCtx = zhttp.ReqCtx;
pub const std_options: std.Options = .{
.enable_segfault_handler = false,
.signal_stack_size = null,
};
fn usage() void {
std.debug.print(
\\builtin_middlewares
\\
\\Usage:
\\ zig build examples && ./zig-out/bin/zhttp-example-builtin_middlewares --port=8080
\\ zig build examples-check # runs `--smoke`
\\
\\Options:
\\ --port=8080
\\ --smoke
\\ --help
\\
\\Endpoints:
\\ GET /public
\\ GET /static/hello.txt
\\
, .{});
}
const Public = struct {
pub const Info: zhttp.router.EndpointInfo = .{
.operations = &.{ zhttp.operations.Cors, zhttp.operations.Static },
};
pub fn call(comptime rctx: ReqCtx, req: rctx.T()) !zhttp.Res {
const rid = req.middlewareDataConst("rid").value[0..];
const body = try std.fmt.allocPrint(req.allocator(), "public rid={s}\n", .{rid});
return zhttp.Res.text(200, body);
}
};
fn readResponse(r: *std.Io.Reader, allocator: std.mem.Allocator) !struct { head: []u8, body: []u8 } {
var header_buf: std.ArrayList(u8) = .empty;
errdefer header_buf.deinit(allocator);
while (true) {
const line_incl = try r.takeDelimiterInclusive('\n');
try header_buf.appendSlice(allocator, line_incl);
const line = line_incl[0 .. line_incl.len - 1];
if (line.len == 0 or (line.len == 1 and line[0] == '\r')) break;
}
const header = try header_buf.toOwnedSlice(allocator);
const idx = std.mem.indexOf(u8, header, "content-length:") orelse return error.BadResponse;
const line_end = std.mem.indexOfScalarPos(u8, header, idx, '\n') orelse return error.BadResponse;
const len_line = std.mem.trim(u8, header[idx + "content-length:".len .. line_end], " \t\r");
const len = try std.fmt.parseInt(usize, len_line, 10);
const body = try allocator.alloc(u8, len);
try r.readSliceAll(body);
return .{ .head = header, .body = body };
}
fn headerContains(head: []const u8, allocator: std.mem.Allocator, needle_lower: []const u8) !bool {
const lower = try std.ascii.allocLowerString(allocator, head);
defer allocator.free(lower);
return std.mem.indexOf(u8, lower, needle_lower) != null;
}
const CorsMw = zhttp.middleware.Cors(.{ .origins = &.{"http://example.com"} });
const StaticMw = zhttp.middleware.Static(.{ .dir = "examples/static", .mount = "/static" });
const SrvT = zhttp.Server(.{
.middlewares = .{
zhttp.middleware.Logger(.{}),
zhttp.middleware.SecurityHeaders(.{}),
zhttp.middleware.Origin(.{
.origins = &.{"http://example.com"},
.allow_missing = true,
}),
CorsMw,
zhttp.middleware.Etag(.{ .header_behavior = .check_then_add }),
zhttp.middleware.RequestId(.{ .name = "rid" }),
zhttp.middleware.Timeout(.{ .ms = 5000 }),
zhttp.middleware.Compression(.{ .min_size = 999999 }),
StaticMw,
},
.operations = .{
zhttp.operations.Cors,
zhttp.operations.Static,
},
.routes = .{
zhttp.get("/public", Public),
},
});
/// Starts this executable.
pub fn main(init: std.process.Init) !void {
var port: u16 = 8080;
var smoke: bool = false;
var it = try std.process.Args.Iterator.initAllocator(init.minimal.args, init.gpa);
defer it.deinit();
_ = it.next(); // argv[0]
while (it.next()) |arg_z| {
const arg: []const u8 = arg_z;
if (std.mem.eql(u8, arg, "--help")) {
usage();
return;
}
if (std.mem.eql(u8, arg, "--smoke")) {
smoke = true;
continue;
}
if (common.parseKeyVal(arg)) |kv| {
if (std.mem.eql(u8, kv.key, "port")) {
port = try std.fmt.parseInt(u16, kv.val, 10);
} else {
return error.UnknownArg;
}
continue;
}
return error.UnknownArg;
}
if (smoke) {
const io = init.io;
const addr0: std.Io.net.IpAddress = .{ .ip4 = std.Io.net.Ip4Address.loopback(0) };
var actual_port: u16 = 0;
var group: std.Io.Group = .init;
var group_done = false;
defer if (!group_done) {
group.cancel(io);
group.await(io) catch {};
};
try group.concurrent(io, struct {
fn runServer(args: SrvT.RunArgs) std.Io.Cancelable!void {
SrvT.run(args) catch |err| switch (err) {
error.Canceled => return error.Canceled,
else => std.debug.panic("example server run failed: {s}", .{@errorName(err)}),
};
}
}.runServer, .{.{ .gpa = init.gpa, .io = io, .address = addr0, .ctx = {}, .actual_port_out = &actual_port }});
while (actual_port == 0) {
try std.Io.sleep(io, std.Io.Duration.fromMilliseconds(1), .awake);
}
const addr: std.Io.net.IpAddress = .{ .ip4 = std.Io.net.Ip4Address.loopback(actual_port) };
var stream = try std.Io.net.IpAddress.connect(&addr, io, .{ .mode = .stream });
var close_stream = true;
defer if (close_stream) stream.close(io);
var rb: [8 * 1024]u8 = undefined;
var wb: [8 * 1024]u8 = undefined;
var sr = stream.reader(io, &rb);
var sw = stream.writer(io, &wb);
{
const req = "GET /public HTTP/1.1\r\nHost: x\r\nOrigin: http://example.com\r\n\r\n";
try sw.interface.writeAll(req);
try sw.interface.flush();
const resp = try readResponse(&sr.interface, init.gpa);
defer init.gpa.free(resp.head);
defer init.gpa.free(resp.body);
try std.testing.expect(try headerContains(resp.head, init.gpa, "access-control-allow-origin: http://example.com"));
try std.testing.expect(try headerContains(resp.head, init.gpa, "x-request-id:"));
try std.testing.expect(try headerContains(resp.head, init.gpa, "x-content-type-options: nosniff"));
try std.testing.expect(std.mem.startsWith(u8, resp.body, "public rid="));
}
{
const req = "GET /public HTTP/1.1\r\nHost: x\r\nOrigin: http://forbidden.example\r\n\r\n";
try sw.interface.writeAll(req);
try sw.interface.flush();
const resp = try readResponse(&sr.interface, init.gpa);
defer init.gpa.free(resp.head);
defer init.gpa.free(resp.body);
try std.testing.expect(std.mem.startsWith(u8, resp.head, "HTTP/1.1 403"));
try std.testing.expectEqualStrings("forbidden origin\n", resp.body);
}
{
const req = "GET /static/hello.txt HTTP/1.1\r\nHost: x\r\n\r\n";
try sw.interface.writeAll(req);
try sw.interface.flush();
const resp = try readResponse(&sr.interface, init.gpa);
defer init.gpa.free(resp.head);
defer init.gpa.free(resp.body);
try std.testing.expectEqualStrings("hello\n", resp.body);
}
stream.close(io);
close_stream = false;
group.cancel(io);
group.await(io) catch {};
group_done = true;
return;
}
const addr: std.Io.net.IpAddress = .{ .ip4 = std.Io.net.Ip4Address.loopback(port) };
std.debug.print("listening on http://127.0.0.1:{d}\n", .{port});
try SrvT.run(.{ .gpa = init.gpa, .io = init.io, .address = addr, .ctx = {} });
}