Skip to content

Commit

Permalink
Add subdomain offset setting
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
gmethvin committed Jan 21, 2013
1 parent 8beb1f2 commit ba00e23
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 6 deletions.
17 changes: 11 additions & 6 deletions lib/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

/**
Expand Down
50 changes: 50 additions & 0 deletions test/req.subdomains.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
})
})
})
})
})

0 comments on commit ba00e23

Please sign in to comment.