-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandler.js
More file actions
83 lines (78 loc) · 2.65 KB
/
Copy pathhandler.js
File metadata and controls
83 lines (78 loc) · 2.65 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
exports.handler = (function() {
var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs'),
config = require('./config').config;
function serve(req, res) {
var uripath = url.parse(req.url).pathname
.replace(new RegExp('/$', 'g'), '/index.html');
var host = req.headers.host;
if(config.redirect && config.redirect[host]) {
res.writeHead(302, {'Location': 'http://'+config.redirect[host]});
res.write('302 Location: http://'+config.redirect[host]+'\n');
res.end();
return;
}
console.log(host);
console.log(req.url);
console.log(uripath);
var filename;
if(config.pathHandler && config.pathHandler[host + uripath]) {
console.log('found handler:'+config.pathHandler[host + uripath]);
return require(config.pathHandler[host + uripath]+'/handler').handler.serve(req, res, config.pathHandler[host + uripath]);
} else if (config.handler && config.handler[host]) {
console.log('found handler:'+config.handler[host]);
return require(config.handler[host]+'/handler').handler.serve(req, res, config.handler[host]);
} else if(config.path && config.path[host + uripath]) {
filename = config.path[host + uripath];
} else if(config.host && config.host[host]) {
filename = config.host[host] + uripath;
} else {
filename = config.default + uripath;
}
var contentType;
if(/\.appcache$/g.test(uripath)) {
contentType='text/cache-manifest';
} else if(/\.html$/g.test(uripath)) {
contentType='text/html';
} else if(/\.css$/g.test(uripath)) {
contentType='text/css';
} else if(/\.js$/g.test(uripath)) {
contentType='text/javascript';
} else if(/\.png$/g.test(uripath)) {
contentType='image/png';
} else if(/\.ico$/g.test(uripath)) {
contentType='image/png';
} else {
contentType='text/plain';
}
console.log(filename);
console.log(contentType);
path.exists(filename, function(exists) {
if(!exists) {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.write('404 Not Found\n'+filename);
res.end();
return;
}
fs.readFile(filename, 'binary', function(err, file) {
if(err) {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end(err + '\n');
return;
}
res.writeHead(200, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Content-Type': contentType
});
res.write(file, 'binary');
res.end();
});
})
}
return {
serve: serve
};
})();