The actual middleware layer.

@param {Request} req Incoming HTTP request.
@param {Response} res Outgoing HTTP response.
@param {Function} next Middleware continuation.
@api private
421664
function intercept(req, res, next) {
    if (
         !route.test(req.url)           // Incorrect URL.
      || !req.headers.authorization     // Missing authorization.
      || options.method !== req.method  // Invalid method.
    ) return next();

    //
    // Handle unauthorized requests.
    //
    if (authorization !== req.headers.authorization) {
      res.statusCode = 401;
      res.setHeader('Content-Type', 'application/json');

      return res.end(JSON.stringify({
        ok: false,
        reason: [
          'I am programmed to protect, and sacrifice if necessary.',
          'Feel the power of my lazers! Pew pew!'
        ].join(' ')
      }));
    }

    var primus = this
      , buff = '';

    if (typeof options.middleware === 'function') {
      options.middleware(primus, parse, req, res, next);
    } else {
      //
      // Receive the data from the socket. The `setEncoding` ensures that Unicode
      // chars are correctly buffered and parsed before the `data` event is
      // emitted.
      //
      req.setEncoding('utf8');
      req.on('data', function data(chunk) {
        buff += chunk;
      }).once('end', function end() {
        parse(primus, buff, res);
      });
    }
  }
617252
function(arr, req, res, indx, cb) {
    if (arr.length === indx) {
      cb();
    } else {
      arr[indx](req, res, function() {
        middleware(arr, req, res, ++indx, cb);
      });
    }
  }
465187
function (req, res) {
		LOG.warn('handle_request');

		// attach custom res methods (borrowed from express)
		res = UTIL.mixin(res, response);

		LOG.sys('HTTP req received, header', 'SR.REST');
		LOG.sys(req.headers, 'SR.REST');
		
		var content_type = req.headers['content-type'];

		// NOTE: multi-part needs to be handled first, because req.on('data') will not be able to process correctly
		if (typeof content_type === 'string' && content_type.startsWith('multipart/form-data; boundary=')) { 
			LOG.warn('parsing form request...', 'SR.REST');
			route(req, res);
			return;
		}
		
		// temp buffer for incoming request
		var data = '';
		var JSONobj = undefined;
		
		req.on('data', function (chunk) {
			data += chunk;
		});

		req.on('end', function () {
			
			var JSONobj = undefined;
			
			try {
				if (data !== '') {
						
					if (content_type.startsWith('application/x-www-form-urlencoded')) {
						JSONobj = qs.parse(data);
					} else if (content_type.startsWith('application/json')) {
						JSONobj = UTIL.convertJSON(decodeURIComponent(data));
					} else if (content_type.startsWith('application/sdp')) {
						JSONobj = data;
					} else {
						var msg = 'content type not known: ' + content_type;
						LOG.warn(msg, 'SR.REST');
						SR.REST.reply(res, msg);
						//res.writeHead(200, {'Content-Type': 'text/plain'});
						//res.end(msg);
						return;
					}
				}
			} catch (e) {
				var msg = 'JSON parsing error for data: ' + data + '\n content_type: ' + content_type;
				LOG.error(msg, 'SR.REST');
				//res.writeHead(200, {'Content-Type': 'text/plain'});
				//res.end(msg);
				SR.REST.reply(res, msg);
				return;
			}

			route(req, res, JSONobj);
		})
	}
1327841
function submissions(req, res, next) {
  var params = {
    formId: req.params.id
  };

  logger.debug("Middleware: form submissions: ", {params: params});

  forms.getSubmissions(req.connectionOptions, params, function(err, getSubmissionResponse) {
    if (err) {
      logger.error("Middleware: form submissions ", {error: err});
    }
    getSubmissionResponse = getSubmissionResponse || {};
    req.appformsResultPayload = {
      data: getSubmissionResponse.submissions,
      type: constants.resultTypes.submissions
    };

    next(err);
  });
}
479540
function corsPreflight (req, res, next) {
  if (req.method === "OPTIONS") {
    util.debug("OPTIONS %s is a CORS preflight request. Sending HTTP 200 response.", req.path);
    res.send();
  }
  else {
    next();
  }
}
529851
function reqrtn(req, res) {
    if (req && req._headers) {
        throw new Error('Received response object where request object was expected');
    }
    this.req = req;
    this.res = res;
    this.data = {
    //localHostIpArray:['localhost','127.0.0.1','::1']
    };
    this.isClientInputLoaded = false;
}
1154540
function call(handle, route, err, req, res, next) {
  var arity = handle.length;
  var hasError = Boolean(err);

  debug('%s %s : %s', handle.name || '<anonymous>', route, req.originalUrl);

  try {
    if (hasError && arity === 4) {
      // error-handling middleware
      handle(err, req, res, next);
      return;
    } else if (!hasError && arity < 4) {
      // request-handling middleware
      handle(req, res, next);
      return;
    }
  } catch (e) {
    // reset the error
    err = e;
  }

  // continue
  next(err);
}
186691
function middlewareF (req, res, end) {
    var index = 0

    // inject stats middleware
    if (middlewareF.options && middlewareF.options.stats) {
      middlewareF.stack = middlewareF.stack.map(function (mw) {
        var fn
        if (typeof mw === 'object') {
          var key = Object.keys(mw)[0]
          if (!mw[key].stats) {
            fn = {}
            fn[key] = middlewareF.options.stats(mw[key])
          }
        } else {
          if (!mw.stats) {
            fn = middlewareF.options.stats(mw)
          }
        }
        return fn
      })
    }

    // looping over all middleware functions defined by stack
    ;(function next (err) {
      var arity
      var middleware = middlewareF.stack[index++] // obtain the current middleware from the stack

      if (!middleware) {
        // we are at the end of the stack
        end && end(err)
        return
      } else {
        // extract middleware from object
        if (typeof (middleware) === 'object') {
          var name = Object.keys(middleware)[0]
          if (typeof (middleware[name]) === 'function') {
            middleware = middleware[name]
          } else {
            middleware = function (req, res, next) {
              next(new Error('missing middleware'))
            }
          }
        }

        try {
          arity = middleware.length // number of arguments function middleware requires
          // handle errors
          if (err) {
            // If the middleware function contains 4 arguments than this will act as an "error trap"
            if (arity === 4) {
              middleware(err, req, res, function (err) {
                nextTick(next, err)
              })
            } else {
              // otherwise check the next middleware
              next(err)
            }
          } else if (arity < 4) {
            // process non "error trap" stack
            middleware(req, res, function (err) {
              nextTick(next, err)
            })
          } else {
            // loop over "error traps" if no error `err` is set.
            next()
          }
        } catch (e) {
          next(e)
        }
      }
    })()
  }
1000047
function search(req, res, next) {
  var queryParams = req.body;

  logger.debug("Middleware Submission Search ", {params: queryParams});

  forms.submissionSearch(req.connectionOptions, queryParams, _getSubmissionsResultHandler(req, next));
}
907701
function runMiddlewareStack(stack, req, res, callback) {
  let index = 0;
  // the middleware layer handover callback
  function next(err) {
    // get next middleware callback from stack
    const handle = stack[index++];
    // if no more layers in stack, invoke done callback and exit recursion
    if (!handle) {
      callback(err);
      return;
    }
    let error = err;
    // call the middleware handler
    try {
      if (err && handle.length === 4) {
        // there is an error and it's an error-handling middleware
        handle(err, req, res, next);
        return;
      } else if (!err && handle.length < 4) {
        // no error and it's a request-handling middleware
        handle(req, res, next);
        return;
      }
    } catch (e) {
      // if new error thrown, replace the error
      error = e;
    }
    // otherwise skip layer
    next(error);
  }
  // start going through middleware stack
  next();
}
802465
function proxyMiddleware(req, res, next) {
  /*
   * This test is the switch of each request to determine if the request is
   * for a static file to be handled by BrowserSync or a backend request to proxy.
   *
   * The existing test is a standard check on the files extensions but it may fail
   * for your needs. If you can, you could also check on a context in the url which
   * may be more reliable but can't be generic.
   */
  //if (/\.(html|css|js|png|jpg|jpeg|gif|ico|xml|rss|txt|eot|svg|ttf|woff|woff2|cur)(\?((r|v|rel|rev)=[\-\.\w]*)?)?$/.test(req.url)) {
  if (req.url.indexOf('/api/') == -1) {
    next();
  } else {
    proxy.web(req, res);
  }
}
977278
function setContext(req, res, next) {
    currentContext = {req: req, res: res};
    next();
}
405752
function (req, res, next) {
                // Delayed resolution of the isLoggedIn middleware.
                if (server.registry.has('localUserMiddleware')) {
                    const middleware = server.registry.get('localUserMiddleware');
                    middleware.isLoggedInMiddleware()(req, res, next);
                } else {
                    next(new restifyErrors.ForbiddenError(`Server configuration error, 'localUserMiddleware' not found.`));
                }
            }
75424
function (app, next) {
      app.use(function (req, res, next) {
        router.handle(req, res, next);
      });

      next(null, app);
    }
1128812
function OutgoingResponse(stream) {
  OutgoingMessage.call(this);

  this._log = stream._log.child({ component: 'http' });

  this.stream = stream;
  this.statusCode = 200;
  this.sendDate = true;

  this.stream.once('headers', this._onRequestHeaders.bind(this));
}
964742
function extendHttpResponse(res) {
    res = res || express.response;

    function callbackFnFn(verbFunc) {
        return function (next, status) {
            var res = this;
            return function (err, result) {
                if (err) {
                    return next(err);
                }
                if (status) {
                    return res.status(status);
                }
                return verbFunc.call(res, result);
            };
        };
    }

    function laterFnFn(verbFunc) {
        return function (promise, next, status) {
            var res = this;
            return Q.when(promise).then(function (result) {
                if (status) {
                    res.status(status);
                }
                return verbFunc.call(res, result);
            }).fail(next).done();
        };
    }

    //
    // callback helpers
    //

    /**
     * create generic node.js callback function to invoke 'express.response.send()'.
     *
     * ex.
     * ```
     * var fs = require('fs');
     * app.get('/foo', function(req, res, next) {
     *   fs.readFile('foo.txt', res.sendCallbackFn(next));
     * });
     * ```
     * @param {function} next
     * @param {number} [status]
     * @returns {function(err, result)} generic node.js callback which send response.
     * @method
     * @memberOf {express.request}
     */
    res.sendCallbackFn = callbackFnFn(res.send);

    /**
     * create generic node.js callback function to invoke 'express.response.json()'.
     *
     * @param {function} next
     * @param {number} [status]
     * @returns {function(err, result)} generic node.js callback which send 'json' response.
     * @method
     * @memberOf {express.request}
     */
    res.jsonCallbackFn = callbackFnFn(res.json);

    /**
     * create generic node.js callback function to invoke 'express.response.jsonp()'.
     *
     * @param {function} next
     * @param {number} [status]
     * @returns {function(err, result)} generic node.js callback which send 'jsonp' response.
     * @method
     * @memberOf {express.request}
     */
    res.jsonpCallbackFn = callbackFnFn(res.jsonp);

    /**
     * create generic node.js callback function to invoke 'express.response.sendFile()'.
     *
     * @param {function} next
     * @param {number} [status]
     * @returns {function(err, result)} generic node.js callback which send 'sendFile' response.
     * @method
     * @memberOf {express.request}
     */
    res.sendFileCallbackFn = callbackFnFn(res.sendFile);

    /**
     * create generic node.js callback function to invoke 'express.response.redirect()'.
     *
     * @param {function} next
     * @param {number} [status]
     * @returns {function(err, result)} generic node.js callback which send 'redirect' response.
     * @method
     * @memberOf {express.request}
     */
    res.redirectCallbackFn = callbackFnFn(res.redirect);

    /**
     * ex.
     * ```
     * fs.stat('foo.txt', res.renderCallbackFn('stat_view', next));
     * ```
     *
     * @param {string} view
     * @param {function} next
     * @param {number} [status]
     * @returns {function(err, result)}
     * @memberOf {express.response}
     */
    res.renderCallbackFn = function (view, next, status) {
        var res = this;
        return function (err, result) {
            if (err) {
                return next(err);
            }
            if (status) {
                res.status(status);
            }
            return res.render(view, result);
        };
    };

    //
    // promise helpers
    //

    /**
     * promise version to invoke `express.response.send()`.
     *
     * ex.
     * ```
     * var FS = require('q-io/fs');
     * app.get('/foo', function (req, res, next) {
     *   res.sendLater(FS.readFile('foo.txt'), next);
     * })
     * ```
     *
     * @param {promise|*} promise of response.
     * @param {function} next
     * @param {number} [status]
     * @method
     * @memberOf {express.request}
     */
    res.sendLater = laterFnFn(res.send);

    /**
     * promise version of `express.response.json()`.
     *
     * @param {promise|*} promise of 'json' response.
     * @param {function} next
     * @param {number} [status]
     * @method
     * @memberOf {express.request}
     */
    res.jsonLater = laterFnFn(res.json);

    /**
     * promise version of `express.response.jsonp()`.
     *
     * @param {promise|*} promise of 'jsonp' response.
     * @param {function} next
     * @param {number} [status]
     * @method
     * @memberOf {express.request}
     */
    res.jsonpLater = laterFnFn(res.jsonp);

    /**
     * promise version of `express.response.sendFile()`.
     *
     * @param {promise|*} promise of 'sendFile' response.
     * @param {function} next
     * @param {number} [status]
     * @method
     * @memberOf {express.request}
     */
    res.sendFileLater = laterFnFn(res.sendFile);

    /**
     * promise version of `express.response.redirect()`.
     *
     * @param {promise|*} promise of 'redirect' response.
     * @param {function} next
     * @param {number} [status]
     * @method
     * @memberOf {express.request}
     */
    res.redirectLater = laterFnFn(res.redirect);

    /**
     *
     * ex.
     * ```
     * var FS = require('q-io/fs');
     * res.renderLater('stat_view', FS.stat('foo.txt'), next);
     * ```
     *
     * @param {string} view
     * @param {promise|*} promise of 'render' model.
     * @param {function} next
     * @param {number} [status]
     * @memberOf {express.response}
     */
    res.renderLater = function (view, promise, next, status) {
        var res = this;
        return Q.when(promise).then(function (result) {
            if (status) {
                res.status(status);
            }
            return res.render(view, result);
        }).fail(next).done();
    };
}
880368
function(req, res, next) {
        var initialTime = 0,
            receivedReqTime = new Date().getTime();

        req.requestDelay =  receivedReqTime - initialTime;
        var url = req.body.url;

        request.get(url, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                req.rawOntology = body.toString().replace(/(&)([a-z0-9]+)(;)/gi, '$2:');
                next();
            }
        });
    }