Skip to content

Instantly share code, notes, and snippets.

@martin-mok
Forked from jeffrafter/handler.js
Created January 17, 2024 15:56
Show Gist options
  • Save martin-mok/5aa26f3111ffaa74c5512436c98b380d to your computer and use it in GitHub Desktop.
Save martin-mok/5aa26f3111ffaa74c5512436c98b380d to your computer and use it in GitHub Desktop.
Simple HTTP Server and Router in node.js
exports.createHandler = function (method) {
return new Handler(method);
}
Handler = function(method) {
this.process = function(req, res) {
params = null;
return method.apply(this, [req, res, params]);
}
}
var handlerFactory = require('./handler');
var fs = require('fs');
var sys = require('sys');
var parser = require('url');
var handlers = {};
exports.clear = function() {
handlers = {};
}
exports.register = function(url, method) {
handlers[url] = handlerFactory.createHandler(method);
}
exports.route = function(req) {
url = parser.parse(req.url, true);
var handler = handlers[url.pathname];
if (!handler) handler = this.missing(req)
return handler;
}
exports.missing = function(req) {
// Try to read the file locally, this is a security hole, yo /../../etc/passwd
var url = parser.parse(req.url, true);
var path = __dirname + "/public" + url.pathname
try {
data = fs.readFileSync(path);
mime = req.headers.accepts || 'text/html'
return handlerFactory.createHandler(function(req, res) {
res.writeHead(200, {'Content-Type': mime});
res.write(data);
res.close();
});
} catch (e) {
return handlerFactory.createHandler(function(req, res) {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.write("No route registered for " + url.pathname);
res.close();
});
}
}
var sys = require('sys');
var http = require('http');
var router = require('./router');
// Handle your routes here, put static pages in ./public and they will server
router.register('/', function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World');
res.close();
});
// We need a server which relies on our router
var server = http.createServer(function (req, res) {
handler = router.route(req);
handler.process(req, res);
});
// Start it up
server.listen(8000);
sys.puts('Server running');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment