Add subdomain offset setting

Add a setting "subdomain offset" for the app, which can be used to
change the behavior of req.subdomains. This is useful when our "base"
domain contains more than two parts, e.g. example.co.uk, and also
when we are running locally with domains like xxx.local.

The default behavior is still to return all but the last two parts.
This commit is contained in:
Greg Methvin
2013-01-20 00:24:57 -08:00
parent 8beb1f21ef
commit ba00e23630
2 changed files with 61 additions and 6 deletions

View File

@@ -401,18 +401,23 @@ req.__defineGetter__('auth', function(){
/**
* Return subdomains as an array.
*
* For example "tobi.ferrets.example.com"
* would provide `["ferrets", "tobi"]`.
* Subdomains are the dot-separated parts of the host before the main domain of
* the app. By default, the domain of the app is assumed to be the last two
* parts of the host. This can be changed by setting "subdomain offset".
*
* For example, if the domain is "tobi.ferrets.example.com":
* If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
* If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
*
* @return {Array}
* @api public
*/
req.__defineGetter__('subdomains', function(){
return this.get('Host')
.split('.')
.slice(0, -2)
.reverse();
var offset = this.app.get('subdomain offset');
if (offset == null) offset = 2;
return this.get('Host').split('.').reverse().slice(offset);
});
/**

View File

@@ -33,5 +33,55 @@ describe('req', function(){
.expect('[]', done);
})
})
describe('when subdomain offset is set', function(){
describe('when subdomain offset is zero', function(){
it('should return an array with the whole domain', function(done){
var app = express();
app.set('subdomain offset', 0);
app.use(function(req, res){
res.send(req.subdomains);
});
request(app)
.get('/')
.set('Host', 'tobi.ferrets.sub.example.com')
.expect('["com","example","sub","ferrets","tobi"]', done);
})
})
describe('when present', function(){
it('should return an array', function(done){
var app = express();
app.set('subdomain offset', 3);
app.use(function(req, res){
res.send(req.subdomains);
});
request(app)
.get('/')
.set('Host', 'tobi.ferrets.sub.example.com')
.expect('["ferrets","tobi"]', done);
})
})
describe('otherwise', function(){
it('should return an empty array', function(done){
var app = express();
app.set('subdomain offset', 3);
app.use(function(req, res){
res.send(req.subdomains);
});
request(app)
.get('/')
.set('Host', 'sub.example.com')
.expect('[]', done);
})
})
})
})
})