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
// This script sets up a simple HTTP server for a comment box using Deno's Blob Storage for persistence.
// Comments are stored in a JSON array in Blob Storage. When users submit a new comment, it is added to the array.
// The main page displays all stored comments along with a form to submit a new comment.
import { serve } from "https://deno.land/std@0.115.0/http/server.ts";
import { ulid } from "https://cdn.jsdelivr.net/npm/ulid@2.3.5/+esm"; // Unique IDs for comments
import { blob } from "https://esm.town/v/std/blob";
const key = "comments";
async function getComments(): Promise<Array<{ id: string; content: string }>> {
const comments = await blob.getJSON(key) as Array<{ id: string; content: string }> | undefined;
return comments ?? [];
}
async function addComment(content: string) {
const comments = await getComments();
comments.push({ id: ulid(), content });
await blob.setJSON(key, comments);
}
export default async function main(req: Request): Promise<Response> {
if (req.method === "POST") {
const formData = await req.formData();
const content = formData.get("content")?.toString();
if (content) {
await addComment(content);
}
return Response.redirect(req.url);
}
if (req.method === "GET") {
const comments = await getComments();
let html = `
<html>
<head>
<title>Comment Box</title>
<style>
body { font-family: sans-serif; padding: 20px; }
textarea { width: 100%; height: 100px; }
form { margin-bottom: 20px; }
.comment { margin-bottom: 10px; padding: 10px; border: 1px solid #ccc; }
</style>
</head>
<body>
<h1>Comment Box</h1>
<form method="post">
<textarea name="content" required></textarea><br />
<button type="submit">Submit</button>
</form>
<h2>Comments</h2>
${comments.map(c => `<div class="comment">${c.content}</div>`).join('')}
</body>
</html>
`;
return new Response(html, { headers: { "Content-Type": "text/html" } });
}
return new Response("Method not allowed", { status: 405 });
}