-
Notifications
You must be signed in to change notification settings - Fork 1
/
router.js
112 lines (86 loc) · 2.71 KB
/
router.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
var fs = require('fs'),
mime = require('mime'),
path = require('path'),
log4js = require('log4js'),
url = require('url');
var _log = log4js.getLogger('router');
var Router = function(base, routes, store) {
var _self = this;
var _base = base;
var _store = store;
var _map = {
get: {},
post: {}
};
var _pattern = /^(post|get|\*):[\w.-_\/]+$/i;
var _parse = function (routes) {
for (var key in routes) {
if (_pattern.test(key)) {
var paths = key.split(':');
var method = paths[0].toLowerCase();
var path = paths[1];
if (method == '*') {
for (var type in _map) {
_map[type][path] = routes[key];
}
} else {
_map[method][path] = routes[key];
}
}
}
}
this.notfound = function(request, response) {
response.writeHead(404, {})
response.end("Not found")
}
this.route = function route(request, response) {
var incoming = request.headers['x-forwarded-for'] ||
request.connection.remoteAddress;
_log.info ('(' + incoming + ') request: ' + request.url);
_log.debug ('route to: ' + request.method.toLowerCase() + ' - ' + request.url);
var target = request.url == '/' ? '/index.html' : request.url;
var filePath = path.join(__dirname, _base, url.parse(target).pathname);
if (path.existsSync(filePath)) {
// Serve static file
var stat = fs.statSync(filePath);
if (stat.isDirectory()) {
_self.notfound(request, response);
} else {
response.writeHead(200, {
'Content-Type': mime.lookup(filePath),
'Content-Length': stat.size
});
var stream = fs.createReadStream(filePath);
stream.on('data', function (data) {
response.write(data);
});
stream.on('end', function() {
response.end();
});
}
} else {
var method = _map[request.method.toLowerCase()][request.url];
if (method) {
method(request, response, _store);
} else {
var methods = _map[request.method.toLowerCase()];
var match = null;
for (var key in methods) {
var pattern = new RegExp('^' + key + '.*$', 'i');
_log.debug ('url: ' + request.url + ' pattern: ' + pattern);
if (pattern.test(request.url)) {
match = methods[key];
break;
}
}
if (match) {
match(request, response, _store);
} else {
_self.notfound(request, response);
}
}
}
}
_parse(routes);
}
exports.router = Router;