diff --git a/README.md b/README.md index 6978548..e238daf 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,8 @@ corresponding to each wildcard (or capture group if RegExp object provided) and `hostname` that was matched. ```js -// for match of "foo.bar.example.com" against "*.*.example.com": +// for match of "foo.bar.example.com:8080" against "*.*.example.com": +req.vhost.host === 'foo.bar.example.com:8080' req.vhost.hostname === 'foo.bar.example.com' req.vhost.length === 2 req.vhost[0] === 'foo' diff --git a/index.js b/index.js index 3d0254d..60059e5 100644 --- a/index.js +++ b/index.js @@ -42,20 +42,14 @@ module.exports = function vhost(hostname, server){ var regexp = hostregexp(hostname) return function vhost(req, res, next){ - var hostname = hostnameof(req) + var vhostdata = vhostof(req, regexp) - if (!hostname) { - return next() - } - - var match = regexp.exec(hostname) - - if (!match) { + if (!vhostdata) { return next() } // populate - req.vhost = data(match) + req.vhost = vhostdata // handle handle(req, res, next) @@ -84,27 +78,6 @@ function createHandle(server){ throw new TypeError('argument server is unsupported') } -/** - * Create the value for req.vhost from a RegExp match. - * - * @param (object} match - * @return {object} - * @api private - */ - -function data(match){ - var obj = Object.create(null) - - obj.hostname = match.input - obj.length = match.length - 1 - - for (var i = 1; i < match.length; i++) { - obj[i - 1] = match[i] - } - - return obj -} - /** * Get hostname of request. * @@ -168,3 +141,39 @@ function hostregexp(val){ return new RegExp(source, 'i') } + +/** + * Get the vhost data of the request for RegExp + * + * @param (object} req + * @param (RegExp} regexp + * @return {object} + * @api private + */ + +function vhostof(req, regexp){ + var host = req.headers.host + var hostname = hostnameof(req) + + if (!hostname) { + return + } + + var match = regexp.exec(hostname) + + if (!match) { + return + } + + var obj = Object.create(null) + + obj.host = host + obj.hostname = hostname + obj.length = match.length - 1 + + for (var i = 1; i < match.length; i++) { + obj[i - 1] = match[i] + } + + return obj +} diff --git a/test/test.js b/test/test.js index 2bd1aa1..779606f 100644 --- a/test/test.js +++ b/test/test.js @@ -167,7 +167,7 @@ describe('vhost(hostname, server)', function(){ request(app) .get('/') .set('Host', 'user-bob.foo.com:8080') - .expect(200, '[["0","bob"],["1","foo"],["hostname","user-bob.foo.com"],["length",2]]', done) + .expect(200, '[["0","bob"],["1","foo"],["host","user-bob.foo.com:8080"],["hostname","user-bob.foo.com"],["length",2]]', done) }) }) @@ -210,7 +210,7 @@ describe('vhost(hostname, server)', function(){ request(app) .get('/') .set('Host', 'user-bob.foo.com:8080') - .expect(200, '[["0","bob"],["1","foo"],["hostname","user-bob.foo.com"],["length",2]]', done) + .expect(200, '[["0","bob"],["1","foo"],["host","user-bob.foo.com:8080"],["hostname","user-bob.foo.com"],["length",2]]', done) }) })