Skip to content

Commit

Permalink
add default redirect behaviour
Browse files Browse the repository at this point in the history
  • Loading branch information
tj committed Jul 4, 2012
1 parent 68e3381 commit 5aeae29
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
18 changes: 17 additions & 1 deletion lib/send.js
Expand Up @@ -259,6 +259,22 @@ SendStream.prototype.isFresh = function(){
return fresh(this.req.headers, this.res._headers);
};

/**
* Redirect to `path`.
*
* @param {String} path
* @api private
*/

SendStream.prototype.redirect = function(path){
if (this.listeners('directory').length) return this.emit('directory');
var res = this.res;
path += '/';
res.statusCode = 301;
res.setHeader('Location', path);
res.end('Redirecting to ' + utils.escape(path));
};

/**
* Pipe to `res.
*
Expand Down Expand Up @@ -302,7 +318,7 @@ SendStream.prototype.pipe = function(res){
debug('stat "%s"', path);
fs.stat(path, function(err, stat){
if (err) return self.onStatError(err);
if (stat.isDirectory()) return self.emit('directory', stat);
if (stat.isDirectory()) return self.redirect(self.path);
self.send(path, stat);
});

Expand Down
20 changes: 18 additions & 2 deletions test/send.js
Expand Up @@ -114,11 +114,27 @@ describe('send(file).pipe(res)', function(){
.end(done);
})

describe('when no "directory" listeners are present', function(){
it('should respond with a redirect', function(done){
var app = http.createServer(function(req, res){
send(req.url)
.root('test/fixtures')
.pipe(res);
});

request(app)
.get('/pets')
.expect(301)
.expect('Location', '/pets/')
.expect('Redirecting to /pets/')
.end(done);
})
})

describe('when no "error" listeners are present', function(){
it('should respond to errors directly', function(done){
var app = http.createServer(function(req, res){
send('test/fixtures' + req.url)
.pipe(res);
send('test/fixtures' + req.url).pipe(res);
});

request(app)
Expand Down

0 comments on commit 5aeae29

Please sign in to comment.