Skip to content

Commit

Permalink
Add res.redirect and res.internalRedirect to node-router response obj…
Browse files Browse the repository at this point in the history
…ects.
  • Loading branch information
creationix committed Mar 22, 2010
1 parent b95c617 commit 736ef63
Showing 1 changed file with 48 additions and 29 deletions.
77 changes: 48 additions & 29 deletions lib/node-router.js
Expand Up @@ -135,8 +135,19 @@ exports.getServer = function getServer(logger) {
// Enable logging on all requests using common-logger style
logify(req, res, logger);

var uri = url_parse(req.url);
var path = uri.pathname;
var uri, path;

// Performs an HTTP 302 redirect
res.redirect = function redirect(location) {
res.writeHead(302, {"Location": location});
res.close();
}

// Performs an internal redirect
res.innerRedirect = function innerRedirect(location) {
req.url = location;
doRoute();
}

res.simpleText = function (code, body, extra_headers) {
res.writeHead(code, (extra_headers || []).concat(
Expand Down Expand Up @@ -170,43 +181,51 @@ exports.getServer = function getServer(logger) {
notFound(req, res, message);
};

for (var i = 0, l = routes.length; i < l; i += 1) {
var route = routes[i];
if (req.method === route.method) {
var match = path.match(route.pattern);
if (match && match[0].length > 0) {
match.shift();
match = match.map(unescape);
match.unshift(res);
match.unshift(req);
if (route.format !== undefined) {
var body = "";
req.setBodyEncoding('utf8');
req.addListener('data', function (chunk) {
body += chunk;
});
req.addListener('end', function () {
if (route.format === 'json') {
body = JSON.parse(unescape(body));
}
match.push(body);
route.handler.apply(null, match);
});
function doRoute() {
uri = url_parse(req.url);
path = uri.pathname;

for (var i = 0, l = routes.length; i < l; i += 1) {
var route = routes[i];
if (req.method === route.method) {
var match = path.match(route.pattern);
if (match && match[0].length > 0) {
match.shift();
match = match.map(unescape);
match.unshift(res);
match.unshift(req);
if (route.format !== undefined) {
var body = "";
req.setBodyEncoding('utf8');
req.addListener('data', function (chunk) {
body += chunk;
});
req.addListener('end', function () {
if (route.format === 'json') {
body = JSON.parse(unescape(body));
}
match.push(body);
route.handler.apply(null, match);
});
return;
}
route.handler.apply(null, match);
return;
}
route.handler.apply(null, match);
return;
}
}
}

notFound(req, res);
notFound(req, res);
}
doRoute();

});

function listen(port, host) {
port = port || 8080;
host = host || "127.0.0.1";
server.listen(port, host);
logger("Server at http://" + (host || "127.0.0.1") + ":" + port.toString() + "/");
logger("node-router server instance at http://" + host + ":" + port + "/");
}

function close() {
Expand Down

0 comments on commit 736ef63

Please sign in to comment.