Skip to content
Browse files

Merge pull request #36 from yawnt/http-redirect

res.redirect()
  • Loading branch information...
2 parents 942cc6d + cfd897c commit 7d5b5657eee209c253b0bd0f49313db65039cd04 @pksunkara pksunkara committed Jul 19, 2012
Showing with 50 additions and 1 deletion.
  1. +9 −1 examples/simple/simple.js
  2. +17 −0 lib/response-stream.js
  3. +24 −0 test/simple-test.js
View
10 examples/simple/simple.js
@@ -19,7 +19,7 @@ var server = union.createServer({
});
router.get('/foo', function () {
- this.res.writeHead(200, { 'Content-Type': 'text/plain' })
+ this.res.writeHead(200, { 'Content-Type': 'text/plain' });
this.res.end('hello world\n');
});
@@ -37,6 +37,14 @@ router.post('/foo', { stream: true }, function () {
});
});
+router.get('/redirect', function() {
+ this.res.redirect('http://www.google.com');
+});
+
+router.get('/custom_redirect', function() {
+ this.res.redirect('/foo', 301);
+});
+
server.listen(9090);
console.log('union with director running on 9090');
View
17 lib/response-stream.js
@@ -159,3 +159,20 @@ ResponseStream.prototype.write = function (data) {
this.emit('data', data);
}
};
+
+ResponseStream.prototype.redirect = function(path, status) {
+ var url = '';
+
+ if(~path.indexOf('://')) {
+ url = path;
+ } else {
+ url += this.req.connection.encrypted ? 'https://' : 'http://';
+ url += this.req.headers.host;
+ url += (path[0] === '/') ? path : '/' + path;
+ }
+
+ this.res.writeHead(status || 302, {
+ 'Location': url
+ });
+ this.res.end();
+};
View
24 test/simple-test.js
@@ -48,6 +48,30 @@ vows.describe('union/simple').addBatch({
macros.assertValidResponse(err, res);
assert.equal(body, 'wrote to a stream!');
}
+ },
+ "a GET request to `/redirect`": {
+ topic: function() {
+ request.get({
+ url: 'http://localhost:9090/redirect',
+ followRedirect: false
+ }, this.callback);
+ },
+ "it should redirect to `http://www.google.com`": function(err, res, body) {
+ assert.equal(res.statusCode, 302);
+ assert.equal(res.headers.location, "http://www.google.com");
+ }
+ },
+ "a GET request to `/custom_redirect`": {
+ topic: function() {
+ request.get({
+ url: 'http://localhost:9090/custom_redirect',
+ followRedirect: false
+ }, this.callback);
+ },
+ "it should redirect to `/foo`": function(err, res, body) {
+ assert.equal(res.statusCode, 301);
+ assert.equal(res.headers.location, "http://localhost:9090/foo");
+ }
}
}
}

0 comments on commit 7d5b565

Please sign in to comment.
Something went wrong with that request. Please try again.