Skip to content

Instantly share code, notes, and snippets.

@pschultz
Forked from jeffrafter/handler.js
Last active October 1, 2017 16:06
Show Gist options
  • Save pschultz/9216502 to your computer and use it in GitHub Desktop.
Save pschultz/9216502 to your computer and use it in GitHub Desktop.
Webservice starting point
var parser = require('url');
var handlers = {};
var Handler = function(callback) {
this.process = function(req, res) {
params = null;
return callback.apply(this, [req, res, params]);
}
}
exports.clear = function() {
handlers = {};
}
exports.GET = function(url, callback) {
exports.register('GET', url, callback);
}
exports.POST = function(url, callback) {
exports.register('POST', url, callback);
}
exports.PUT = function(url, callback) {
exports.register('PUT', url, callback);
}
exports.DELETE = function(url, callback) {
exports.register('DELETE', url, callback);
}
exports.register = function(method, url, callback) {
if (typeof handlers[url] === 'undefined') {
handlers[url] = {};
};
handlers[url][method] = new Handler(callback);
}
var fourOhFourHandler = new Handler(function fourOhFour(req, res) {
res.writeHead(404, {});
res.end();
});
var methodNotAllowedHandler = new Handler(function methodNotAllowed(req, res) {
res.writeHead(405, {});
res.end();
});
exports.route = function(req, res) {
url = parser.parse(req.url, true);
var pathHandlers = handlers[url.pathname];
if (!pathHandlers) return fourOhFourHandler;
return pathHandlers[req.method] || methodNotAllowedHandler;
}
var http = require('http');
var router = require('./router');
router.GET('/', function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World');
res.end();
});
var server = http.createServer(function (req, res) {
handler = router.route(req);
handler.process(req, res);
});
port = process.env['PORT'] || 80
server.listen(port);
console.log("Listening on port " + port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment