Skip to content

Instantly share code, notes, and snippets.

@escusado
Created April 16, 2012 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save escusado/2402116 to your computer and use it in GitHub Desktop.
Save escusado/2402116 to your computer and use it in GitHub Desktop.
// var sys = require('sys'),
// http = require('http'),
// url = require('url'),
// terminal = require('child_process').spawn('bash'),
// response,
// index;
/*
var createServer = function(){
http.createServer(function(req, res) {
var url_parts = url.parse(req.url);
var route = url_parts.pathname;
response = '';
res.writeHeader(200, {"Content-Type": "text/html"});
if(route == '/'){
console.log(route);
response = index;
res.end(response);
}
if(route == '/darken'){
console.log(route);
terminal.stdout.on('data', function (data) {
res.end(data);
return
});
terminal.stdin.write('echo -e "#main\n :color darken(#fff,9)" | ~/.gem/ruby/1.8/gems/sass-3.1.15/bin/sass -t compact');
terminal.stdin.end();
}
}).listen(8000);
}*/
/**
* Node.JS Sinatra Style Routing
*/
var routes = {}
, http = require('http')
, parse = require('url').parse
, server = http.createServer()
, fs = require('fs')
, sys = require('sys')
, terminal = require('child_process').spawn('bash');
/**
* @class http.ServerResponse
* @method send
* @param {Object/String} message Data to send
* @optional {Number} code HTTP Status Code
* @optionsal {String} type Content-Type
*/
http.ServerResponse.prototype.send = function(message, code, type) {
code = code || 200;
type = type || 'text/html';
// if (/object/.test(typeof(message))) {
// message = JSON.stringify(message);
// type = 'application/json';
// };
this.writeHead(code, { 'Content-Type': 'text/html' });
this.end(message);
};
/**
* @method addRoute
* @param {String} path URL endpoint
* @param {String} method HTTP Method
* @param {Function} fn Callback function
*/
function addRoute(path, method, fn) {
routes[path] = {};
routes[path][method] = fn;
};
/**
* @method route
* @param {Object} request HTTP Request object
* @param {Object} response HTTP Response object
*/
function route(request, response) {
var pathname = parse(request.url).pathname;
if (routes[pathname] && routes[pathname][request.method]) {
var handle = routes[pathname][request.method];
handle.apply(this, arguments);
} else {
};
};
['GET','PUT','POST','DELETE'].forEach(function(method) {
http.Server.prototype[method.toLowerCase()] = function(path, callback) {
addRoute(path, method, callback);
}
});
server.on('request', function theHandler(request, response) {
route(request, response);
});
/**
* Demo
*/
server.get('/', function(request, response) {
var k = fs.readFileSync('./index.html','utf8');
response.send( k );
});
server.get('/routes', function(request, response) {
response.send(routes);
});
server.listen(8000);
/* EOF */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment