-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.js
95 lines (85 loc) · 2.42 KB
/
http.js
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
// thanks, gpt :D
const express = require('express');
const app = express();
const port = 3000;
const messageLengthLimit = 60;
const fs = require('fs/promises');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const messagesFilePath = '/var/messages.json';
function escapeHtml(text) {
return text.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
async function readMessages() {
const data = await fs.readFile(messagesFilePath, 'utf8');
return JSON.parse(data);
}
async function writeMessages(messages) {
await fs.writeFile(messagesFilePath, JSON.stringify(messages));
}
app.post('/add', async (req, res) => {
const message = req.body.msg;
if (typeof message === 'string' && message.length <= messageLengthLimit) {
try {
const messages = await readMessages();
messages.push(escapeHtml(message));
await writeMessages(messages);
res.redirect('/');
} catch (err) {
console.error('Error processing request:', err);
res.status(500).send('Server error');
}
} else {
res.status(400).send('Invalid message');
}
});
app.get('*', async (req, res) => {
try {
let messages = await readMessages();
messages = messages.reverse();
const messagesHtml = messages.map(msg => `<li>${msg}</li>`).join('');
const html = `<meta charset='utf8'>
<style>
ul {
list-style-type: none;
padding: 0;
}
form { font-size: 16px; }
li {
padding: 10px;
background: beige;
border: 1px dashed black;
margin-bottom: 10px;
font-size: 16px;
}
input {
width: 100%;
max-width: 600px;
padding: 10px;
font-size: 16px;
}
</style>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vieraskirja</title>
<h1>Vieraskirja</h1>
<form action='/add' method='post'>
Viesti:<br>
<input type='text' name='msg' maxlength='${messageLengthLimit}' autofocus>
<br><br>
<input type='submit' value='Lisää vieraskirjaan'>
</form>
<hr>
<ul>` + messagesHtml + `</ul>`;
res.send(html);
} catch (err) {
console.error('Error reading messages file:', err);
res.status(500).send('Server error');
}
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});