Skip to content

Instantly share code, notes, and snippets.

@thisivan
Created November 4, 2010 17:13
Show Gist options
  • Save thisivan/662787 to your computer and use it in GitHub Desktop.
Save thisivan/662787 to your computer and use it in GitHub Desktop.
The code from the talk I gave today about Node.js
/*
* Rest Calculator Server
*
* Based on "Building a Simple Web Service" screencast
* from thinkvitamin.com
*/
var util = require('util'),
http = require('http');
var ops = {
add : function(a, b) { return a + b },
sub : function(a, b) { return a - b },
mul : function(a, b) { return a * b },
div : function(a, b) { return a / b },
};
function RestCalc (options) {
this.settings = {
port : options.port || 80
};
this.init();
};
RestCalc.prototype.init = function () {
this.httpServer = this.createHTTPServer();
this.httpServer.listen(this.settings.port);
console.log('Server running at http://localhost:' + this.settings.port);
};
RestCalc.prototype.createHTTPServer = function (port) {
var server = http.createServer(function (request, response) {
var parts = request.url.split('/');
var op = ops[parts[1]];
var a = parseInt(parts[2], 10);
var b = parseInt(parts[3], 10);
var result = op ? op(a, b) : 'Invalid Request';
response.writeHead(200, {'Content-Type' : 'text/html'});
response.write('<p>' + result + '</p>');
response.end();
});
return server;
};
module.exports = RestCalc;
/* Server Launcher */
require.paths.unshift(__dirname + '/lib');
var RestCalc = require('rest_calc');
new RestCalc({
port : 8000
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment