-
Notifications
You must be signed in to change notification settings - Fork 0
/
http-middleware.js
65 lines (57 loc) · 1.23 KB
/
http-middleware.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
var http = require('http');
var async = require('async');
var mddl = {
server: null,
middleware: [],
routes: {},
createServer: function () {
mddl.server = http.createServer(mddl.request);
return mddl;
},
listen: function (port, callback) {
mddl.server.listen(port || '80', callback);
},
use: function (a, b) {
if (typeof(a) === 'function') {
if (a.length === 2) {
mddl.routes['/'] = a;
}
else if (a.length === 3) {
mddl.middleware.push({
route: '/',
func: a
});
}
}
else if (typeof(a) === 'string' && typeof(b) === 'function') {
if (b.length === 2) {
mddl.routes[a] = b;
}
else if (b.length === 3) {
mddl.middleware.push({
route: a,
func: b
});
}
}
},
request: function (req, res) {
var route = req.url;
if (mddl.routes[route]) {
async.eachSeries(mddl.middleware, function (mid, nextMid) {
if (mid.route == route || mid.route == '/') {
mid.func(req, res, nextMid);
}
else {
nextMid();
}
}, function () {
mddl.routes[route](req, res);
});
}
else {
res.end('Route ' + route + ' was not found');
}
}
};
module.exports = mddl;