You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
1.1 KiB

  1. /*!
  2. * Connect - vhost
  3. * Copyright(c) 2010 Sencha Inc.
  4. * Copyright(c) 2011 TJ Holowaychuk
  5. * MIT Licensed
  6. */
  7. /**
  8. * Vhost:
  9. *
  10. * Setup vhost for the given `hostname` and `server`.
  11. *
  12. * connect()
  13. * .use(connect.vhost('foo.com', fooApp))
  14. * .use(connect.vhost('bar.com', barApp))
  15. * .use(connect.vhost('*.com', mainApp))
  16. *
  17. * The `server` may be a Connect server or
  18. * a regular Node `http.Server`.
  19. *
  20. * @param {String} hostname
  21. * @param {Server} server
  22. * @return {Function}
  23. * @api public
  24. */
  25. module.exports = function vhost(hostname, server){
  26. if (!hostname) throw new Error('vhost hostname required');
  27. if (!server) throw new Error('vhost server required');
  28. var regexp = new RegExp('^' + hostname.replace(/[^*\w]/g, '\\$&').replace(/[*]/g, '(?:.*?)') + '$', 'i');
  29. if (server.onvhost) server.onvhost(hostname);
  30. return function vhost(req, res, next){
  31. if (!req.headers.host) return next();
  32. var host = req.headers.host.split(':')[0];
  33. if (!regexp.test(host)) return next();
  34. if ('function' == typeof server) return server(req, res, next);
  35. server.emit('request', req, res);
  36. };
  37. };