-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathserver.js
More file actions
60 lines (51 loc) · 1.23 KB
/
server.js
File metadata and controls
60 lines (51 loc) · 1.23 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
'use strict';
const http = require('node:http');
const PORT = 8000;
const user = { name: 'jura', age: 22 };
const routing = {
'/': 'welcome to homepage',
'/user': user,
'/user/name': () => user.name,
'/user/age': () => user.age,
'/user/*': (client, params) => 'parameter=' + params[0],
};
const types = {
object: (o) => JSON.stringify(o),
string: (s) => s,
number: (n) => n + '',
undefined: () => 'not found',
function: (fn, params, client) => fn(client, params),
};
const matching = [];
for (const key in routing) {
if (key.includes('*')) {
const rx = new RegExp(key.replace('*', '(.*)'));
const route = routing[key];
matching.push([rx, route]);
delete routing[key];
}
}
const router = (client) => {
const { url } = client.req;
let route = routing[url];
let params = [];
if (!route) {
for (const rx of matching) {
params = url.match(rx[0]);
if (params) {
params.shift();
route = rx[1];
break;
}
}
}
const type = typeof route;
const renderer = types[type];
return renderer(route, params, client);
};
http
.createServer((req, res) => {
res.end(`${router({ req, res })}`);
})
.listen(PORT);
console.log(`Running server on port ${PORT}`);