Skip to content
Myr

http.js

This file

Path

lib/http.js

503 lines · 10.1 KiB · JavaScript

Last changed by

Added "case sensitive routes" option.Tj Holowaychukbefore adoptiond2adcbd

History of this file

Take it

12/*!3 * Express - HTTPServer4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var qs = require('qs')13  , connect = require('connect')14  , router = require('./router')15  , methods = router.methods.concat(['del', 'all'])16  , view = require('./view')17  , url = require('url')18  , utils = connect.utils;1920/**21 * Expose `HTTPServer`.22 */2324exports = module.exports = HTTPServer;2526/**27 * Server proto.28 */2930var app = HTTPServer.prototype;3132/**33 * Initialize a new `HTTPServer` with optional `middleware`.34 *35 * @param {Array} middleware36 * @api public37 */3839function HTTPServer(middleware){40  connect.HTTPServer.call(this, []);41  this.init(middleware);42};4344/**45 * Inherit from `connect.HTTPServer`.46 */4748app.__proto__ = connect.HTTPServer.prototype;4950/**51 * Initialize the server.52 *53 * @param {Array} middleware54 * @api private55 */5657app.init = function(middleware){58  var self = this;59  this.cache = {};60  this.settings = {};61  this.redirects = {};62  this.isCallbacks = {};63  this._locals = {};64  this.dynamicViewHelpers = {};65  this.errorHandlers = [];6667  this.set('home', '/');68  this.set('env', process.env.NODE_ENV || 'development');6970  // expose objects to each other71  this.use(function(req, res, next){72    req.query = req.query || {};73    res.setHeader('X-Powered-By', 'Express');74    req.app = res.app = self;75    req.res = res;76    res.req = req;77    req.next = next;78    // assign req.query79    if (req.url.indexOf('?') > 0) {80      var query = url.parse(req.url).query;81      req.query = qs.parse(query);82    }83    next();84  });8586  // apply middleware87  if (middleware) middleware.forEach(self.use.bind(self));8889  // use router, expose as app.get(), etc90  var fn = router(function(app){ self.routes = app; }, this);91  this.__defineGetter__('router', function(){92    this.__usedRouter = true;93    return fn;94  });9596  // default locals97  this.locals({98      settings: this.settings99    , app: this100  });101102  // default development configuration103  this.configure('development', function(){104    this.enable('hints');105  });106107  // default production configuration108  this.configure('production', function(){109    this.enable('view cache');110  });111112  // register error handlers on "listening"113  // so that they disregard definition position.114  this.on('listening', this.registerErrorHandlers.bind(this));115116  // route lookup methods117  this.remove = function(url){118    return self.remove.all(url);119  };120121  this.match = function(url){122    return self.match.all(url);123  };124125  this.lookup = function(url){126    return self.lookup.all(url);127  };128129  methods.forEach(function(method){130    self.match[method] = function(url){131      return self.router.match(url, 'all' == method132        ? null133        : method);134    };135136    self.remove[method] = function(url){137      return self.router.remove(url, 'all' == method138        ? null139        : method);140    };141142    self.lookup[method] = function(path){143      return self.router.lookup(path, 'all' == method144        ? null145        : method);146    };147  });148};149150/**151 * When using the vhost() middleware register error handlers.152 */153154app.onvhost = function(){155  this.registerErrorHandlers();156};157158/**159 * Register error handlers.160 *161 * @return {Server} for chaining162 * @api public163 */164165app.registerErrorHandlers = function(){166  this.errorHandlers.forEach(function(fn){167    this.use(function(err, req, res, next){168      fn.apply(this, arguments);169    });170  }, this);171  return this;172};173174/**175 * Proxy `connect.HTTPServer#use()` to apply settings to176 * mounted applications.177 *178 * @param {String|Function|Server} route179 * @param {Function|Server} middleware180 * @return {Server} for chaining181 * @api public182 */183184app.use = function(route, middleware){185  var app, home, handle;186187  if ('string' != typeof route) {188    middleware = route, route = '/';189  }190191  // express app192  if (middleware.handle && middleware.set) app = middleware;193194  // restore .app property on req and res195  if (app) {196    app.route = route;197    middleware = function(req, res, next) {198      var orig = req.app;199      app.handle(req, res, function(err){200        req.app = res.app = orig;201        next(err);202      });203    };204  }205206  connect.HTTPServer.prototype.use.call(this, route, middleware);207208  // mounted an app, invoke the hook209  // and adjust some settings210  if (app) {211    home = app.set('home');212    if ('/' == home) home = '';213    app.set('home', app.route + home);214    app.parent = this;215    if (app.__mounted) app.__mounted.call(app, this);216  }217218  return this;219};220221/**222 * Assign a callback `fn` which is called223 * when this `Server` is passed to `Server#use()`.224 *225 * Examples:226 *227 *    var app = express.createServer()228 *      , blog = express.createServer();229 *230 *    blog.mounted(function(parent){231 *      // parent is app232 *      // "this" is blog233 *    });234 *235 *    app.use(blog);236 *237 * @param {Function} fn238 * @return {Server} for chaining239 * @api public240 */241242app.mounted = function(fn){243  this.__mounted = fn;244  return this;245};246247/**248 * See: view.register.249 *250 * @return {Server} for chaining251 * @api public252 */253254app.register = function(){255  view.register.apply(this, arguments);256  return this;257};258259/**260 * Register the given view helpers `obj`. This method261 * can be called several times to apply additional helpers.262 *263 * @param {Object} obj264 * @return {Server} for chaining265 * @api public266 */267268app.helpers =269app.locals = function(obj){270  utils.merge(this._locals, obj);271  return this;272};273274/**275 * Register the given dynamic view helpers `obj`. This method276 * can be called several times to apply additional helpers.277 *278 * @param {Object} obj279 * @return {Server} for chaining280 * @api public281 */282283app.dynamicHelpers = function(obj){284  utils.merge(this.dynamicViewHelpers, obj);285  return this;286};287288/**289 * Map the given param placeholder `name`(s) to the given callback `fn`.290 *291 * Param mapping is used to provide pre-conditions to routes292 * which us normalized placeholders. For example ":user_id" may293 * attempt to load the user from the database, where as ":num" may294 * pass the value through `parseInt(num, 10)`.295 *296 * When the callback function accepts only a single argument, the297 * value of placeholder is passed:298 *299 *    app.param('page', function(n){ return parseInt(n, 10); });300 *301 * After which "/users/:page" would automatically provide us with302 * an integer for `req.params.page`. If desired we could use the callback303 * signature shown below, and immediately `next(new Error('invalid page'))`304 * when `parseInt` fails.305 *306 * Alternatively the callback may accept the request, response, next, and307 * the value, acting like middlware:308 *309 *     app.param('userId', function(req, res, next, id){310 *       User.find(id, function(err, user){311 *         if (err) {312 *           next(err);313 *         } else if (user) {314 *           req.user = user;315 *           next();316 *         } else {317 *           next(new Error('failed to load user'));318 *         }319 *       });320 *     });321 *322 * Now every time ":userId" is present, the associated user object323 * will be loaded and assigned before the route handler is invoked.324 *325 * @param {String|Array} name326 * @param {Function} fn327 * @return {Server} for chaining328 * @api public329 */330331app.param = function(name, fn){332  if (Array.isArray(name)) {333    name.forEach(function(name){334      this.param(name, fn);335    }, this);336  } else {337    if (':' == name[0]) name = name.substr(1);338    this.routes.param(name, fn);339  }340  return this;341};342343/**344 * Assign a custom exception handler callback `fn`.345 * These handlers are always _last_ in the middleware stack.346 *347 * @param {Function} fn348 * @return {Server} for chaining349 * @api public350 */351352app.error = function(fn){353  this.errorHandlers.push(fn);354  return this;355};356357/**358 * Register the given callback `fn` for the given `type`.359 *360 * @param {String} type361 * @param {Function} fn362 * @return {Server} for chaining363 * @api public364 */365366app.is = function(type, fn){367  if (!fn) return this.isCallbacks[type];368  this.isCallbacks[type] = fn;369  return this;370};371372/**373 * Assign `setting` to `val`, or return `setting`'s value.374 * Mounted servers inherit their parent server's settings.375 *376 * @param {String} setting377 * @param {String} val378 * @return {Server|Mixed} for chaining, or the setting value379 * @api public380 */381382app.set = function(setting, val){383  if (val === undefined) {384    if (this.settings.hasOwnProperty(setting)) {385      return this.settings[setting];386    } else if (this.parent) {387      return this.parent.set(setting);388    }389  } else {390    this.settings[setting] = val;391    return this;392  }393};394395/**396 * Check if `setting` is enabled.397 *398 * @param {String} setting399 * @return {Boolean}400 * @api public401 */402403app.enabled = function(setting){404  return !!this.set(setting);405};406407/**408 * Check if `setting` is disabled.409 *410 * @param {String} setting411 * @return {Boolean}412 * @api public413 */414415app.disabled = function(setting){416  return !this.set(setting);417};418419/**420 * Enable `setting`.421 *422 * @param {String} setting423 * @return {Server} for chaining424 * @api public425 */426427app.enable = function(setting){428  return this.set(setting, true);429};430431/**432 * Disable `setting`.433 *434 * @param {String} setting435 * @return {Server} for chaining436 * @api public437 */438439app.disable = function(setting){440  return this.set(setting, false);441};442443/**444 * Redirect `key` to `url`.445 *446 * @param {String} key447 * @param {String} url448 * @return {Server} for chaining449 * @api public450 */451452app.redirect = function(key, url){453  this.redirects[key] = url;454  return this;455};456457/**458 * Configure callback for the given `env`.459 *460 * @param {String} env461 * @param {Function} fn462 * @return {Server} for chaining463 * @api public464 */465466app.configure = function(env, fn){467  if ('function' == typeof env) {468    fn = env, env = 'all';469  }470  if ('all' == env || env == this.settings.env) {471    fn.call(this);472  }473  return this;474};475476// Generate routing methods477478function generateMethod(method){479  app[method] = function(path){480    var self = this;481482    // Lookup483    if (1 == arguments.length) {484      return this.router.lookup(path, 'all' == method485        ? null486        : method);487    }488489    // Ensure router is mounted490    if (!this.__usedRouter) this.use(this.router);491492    // Generate the route493    this.routes[method].apply(this, arguments);494    return this;495  };496  return arguments.callee;497}498499methods.forEach(generateMethod);500501// Alias delete as "del"502503app.del = app.delete;