-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
59 lines (51 loc) · 1.59 KB
/
index.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
http = require('http');
url = require('url');
var StringDecoder = require('string_decoder').StringDecoder;
const httpserver = http.createServer(function(req, res) {
reqreshandler(req, res);
});
httpserver.listen(3000, function(){
console.log("Server started, listening on port 3000");
});
var handlers = {};
handlers.hello = function(data, callback){
callback(200, getResponse(false, data.message));
};
handlers[''] = function(data, callback){
s = '';
for( e in handlers) if ( e != '' ) s += ',' + e;
callback(404, getResponse(true, 'Wrong path: ['+data.path+']. Use one of [' + s.substring(1).trim() + ']'));
};
var routes = {
'hello' : handlers.hello,
'' : handlers.help
};
var getResponse = function(error, message) {
return {
'isError' : error,
'message' : message
};
};
var reqreshandler = function(req, res){
// request parsing
var purl = url.parse(req.url);
var pathname = purl.pathname.replace(/^\/+|\/+$/g, '').toLowerCase();
// getting buffer
var buffer = '';
var decoder = new StringDecoder('utf-8');
req.on('data', function(data){
buffer += decoder.write(data);
});
// handle request
req.on('end', function(){
buffer += decoder.end();
var handler = handlers[pathname];
if( typeof(handler) === 'undefined') handler = handlers[''];
handler({'message': buffer, 'path' : pathname}, function(statusCode, pp) {
statusCode = typeof(statusCode) == 'number' ? statusCode : 404;
pp = typeof(pp) == 'object' ? pp : {};
res.writeHead(statusCode, {'Content-Type': 'application/json'});
res.end(JSON.stringify(pp));
});
});
}