-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandler-full.tsx
More file actions
93 lines (83 loc) · 2.62 KB
/
handler-full.tsx
File metadata and controls
93 lines (83 loc) · 2.62 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
function HomePage(): JSX.Element {
return (
<html>
<head>
<title>zigttp-server</title>
</head>
<body>
<h1>zigttp-server</h1>
<p>A tiny JavaScript runtime for HTTP handlers.</p>
<h2>Endpoints:</h2>
<ul>
<li>
<a href="/api/health">GET /api/health</a> - Health check
</li>
<li>
<a href="/api/echo">GET /api/echo</a>{" "}
- Echo request info
</li>
<li>POST /api/json - Echo JSON body</li>
<li>
<a href="/api/compute">GET /api/compute</a>{" "}
- Compute example
</li>
</ul>
</body>
</html>
);
}
function fibonacci(n: number): number {
if (1 >= n) return n; // reversed: TSX parser treats `<` and `<=` as JSX tag open
let a = 0;
let b = 1;
for (const _ of range(2, n + 1)) {
const temp = a + b;
a = b;
b = temp;
}
return b;
}
function handler(req: Request): Response {
const url = req.url;
const method = req.method;
if (url === "/" && method === "GET") {
return Response.html(renderToString(<HomePage />));
}
if (url === "/api/health") {
return Response.json({
status: "ok",
runtime: "zts",
timestamp: Date.now(),
});
}
if (url === "/api/echo") {
return Response.json({
method: method,
url: url,
headers: req.headers,
body: req.body,
});
}
if (url === "/api/json" && method === "POST") {
const body = req.body;
if (!body) {
return Response.json({ error: "No body provided" }, { status: 400 });
}
const result = JSON.tryParse(body);
if (result.isErr()) {
return Response.json({ error: result.unwrapErr() }, { status: 400 });
}
const data = result.unwrap();
return Response.json({ received: data, processed: true });
}
if (url === "/api/compute") {
const n = 30;
const result = fibonacci(n);
return Response.json({ computation: "fibonacci", n: n, result: result });
}
if (url.indexOf("/api/greet/") === 0) {
const name = url.substring("/api/greet/".length);
return Response.json({ greeting: "Hello, " + name + "!" });
}
return Response.json({ error: "Not Found", url: url }, { status: 404 });
}