-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhomework1.js
More file actions
72 lines (58 loc) · 1.9 KB
/
Copy pathhomework1.js
File metadata and controls
72 lines (58 loc) · 1.9 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
var http = require('http');
var url = require('url');
var StringDecoder = require('string_decoder').StringDecoder;
var config = require('./lib/config');
var httpServer = http.createServer((req,res) => {
unifiedServer(req,res);
});
httpServer.listen(config.httpPort,()=>{
console.log('listening port '+config.httpPort);
});
var unifiedServer = (req, res) => {
var parsedUrl = url.parse(req.url, true);
var path = parsedUrl.pathname;
var trimmedPath = path.replace(/^\/+|\/+$/g,'');
var method = req.method.toLowerCase();
var queryStringObject = parsedUrl.query;
var headers = req.headers;
var decoder = new StringDecoder('utf-8');
var buffer = '';
req.on('data',(data) => {
buffer += decoder.write(data);
});
req.on('end',() => {
buffer += decoder.end();
var chosenHandler = typeof(router[trimmedPath]) !== 'undefined' ? router[trimmedPath] : handlers.notFound;
var data = {
'trimmedPath': trimmedPath,
'queryStringObject': queryStringObject,
'headers': headers,
'payload': buffer
};
chosenHandler(data,(statusCode,payload) => {
statusCode = typeof(statusCode) == 'number' ? statusCode : 200;
payload = typeof(payload) == 'object' ? payload : {};
var payloadString = JSON.stringify(payload);
res.setHeader('Content-Type','application/json');
res.writeHead(statusCode);
res.end(payloadString);
console.log('Response: ', statusCode, payloadString);
});
});
};
//handlers
var handlers = {}
handlers.notFound = (data, callback) => {
callback(404);
};
handlers.hello = (data, callback) => {
callback(200, {
'text': 'Hello world',
'homeworkStatus': 'Done'
});
};
//routers
var router = {
'notFound': handlers.notFound,
'hello': handlers.hello
};