-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
46 lines (35 loc) · 1.18 KB
/
server.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
'use strict'
const http = require('http');
const url = require('url');
const Router = require('./router');
var router = new Router;
module.exports = class Server {
get(pathname, callback) {
router.get(pathname, callback);
}
post(pathname, callback) {
router.post(pathname, callback);
}
start(options) {
options = options || {port: 3000};
var server = http.createServer(this.onRequest);
server.listen(options.port);
console.log('Server has started on port ' + options.port + '.');
}
onRequest(req, res) {
var pathname = url.parse(req.url).pathname;
console.log('Request for ' + pathname + ' received.');
if (router.handler.hasOwnProperty(pathname) && typeof router.handler[pathname].callback === 'function') {
if (req.method !== router.handler[pathname].verb) {
res.statusCode = 405;
res.write('405 Method Not Allowed');
res.end();
}
return router.handler[pathname].callback(req, res);
} else {
res.statusCode = 404;
res.write('404 Not Found');
res.end();
}
}
}