-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
93 lines (84 loc) · 2.76 KB
/
server.js
File metadata and controls
93 lines (84 loc) · 2.76 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const { render } = require('./renderer');
const { getHotels } = require('./api');
const PORT = process.env.PORT || 3000;
function serveStatic(res, filePath, contentType) {
try {
const content = fs.readFileSync(filePath, 'utf-8');
res.writeHead(200, { 'Content-Type': contentType });
res.end(content);
} catch {
res.writeHead(404);
res.end('Not found');
}
}
const server = http.createServer((req, res) => {
if (req.url === '/styles.css') {
return serveStatic(res, path.join(__dirname, 'public', 'styles.css'), 'text/css');
}
if (req.url === '/') {
try {
const html = render(path.join(__dirname, 'content', 'index.md'));
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(html);
} catch (err) {
res.writeHead(500);
res.end(`Error: ${err.message}`);
}
return;
}
if (req.url === '/hotels') {
getHotels()
.then(products => {
const markdownPath = path.join(__dirname, 'content', 'hotels.md');
const html = render(markdownPath, { products });
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(html);
})
.catch(err => {
console.error('API error:', err);
res.writeHead(500);
res.end(`Error fetching hotels: ${err.message}`);
});
return;
}
if (req.url.startsWith('/source')) {
const ejs = require('ejs');
const params = new URL(req.url, 'http://localhost').searchParams;
const filePath = params.get('file');
if (!filePath) { res.writeHead(400); res.end('Missing file param'); return; }
const safePath = path.resolve(__dirname, filePath);
if (!safePath.startsWith(__dirname)) { res.writeHead(403); res.end('Forbidden'); return; }
try {
const content = fs.readFileSync(safePath, 'utf-8');
const filename = path.basename(safePath);
const templatePath = path.join(__dirname, 'views', 'source-page.ejs');
const template = fs.readFileSync(templatePath, 'utf-8');
const html = ejs.render(template, { filename, content, filePath }, { filename: templatePath });
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(html);
} catch {
res.writeHead(404);
res.end('File not found');
}
return;
}
if (req.url === '/extras') {
try {
const html = render(path.join(__dirname, 'content', 'extras.md'));
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(html);
} catch (err) {
res.writeHead(500);
res.end(`Error: ${err.message}`);
}
return;
}
res.writeHead(404);
res.end('Not found');
});
server.listen(PORT, () => {
console.log(`Rendering server running at http://localhost:${PORT}`);
});