Skip to content

Instantly share code, notes, and snippets.

@kwhinnery
Created March 5, 2013 19:28
Show Gist options
  • Save kwhinnery/5093397 to your computer and use it in GitHub Desktop.
Save kwhinnery/5093397 to your computer and use it in GitHub Desktop.
Bublé - a shitty version of Sinatra in 50 lines of node.js code.
var http = require('http'),
url = require('url');
module.exports = function(ctx) {
//Initially the global scope, but will be overridden per request
var context = ctx || this,
routes = {};
//Allow users to handle a GET
context.get = function(route, handler) {
routes.GET = routes.GET || {};
routes.GET[route] = handler;
};
//Set content type for the current response
context.contentType = function(type) {
context.type = type;
context.response.writeHead(200, {
'Content-Type': type
});
};
//Send data for the current response
context.send = function(data) {
context.response.end(data);
};
//create http server
http.createServer(function(request, response) {
//match route, based on request. Right now only does get for exact matches
var handler = routes[request.method][url.parse(request.url).pathname];
//Rebind per request
context.request = request;
context.response = response;
//execute the route if it exists
if (!handler) {
response.writeHead(404, {
'Content-Type': 'text/plain'
});
response.end('Buble hasn\'t butchered that tune yet. Check your URL and try again.');
}
else {
handler.call(context, request, response);
}
}).listen(8080);
console.log('buble is now crooning on port 8080.');
};
require('./buble')();
get('/echo', function() {
contentType('text/plain');
send('You requested: '+request.url);
});
get('/', function() {
contentType('text/html');
send('<html><body><h1>Have I met you yet?</h1></body></html>');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment