Check for request limit on the requesting IP

@access public
@param {object} request Express-style request
@param {object} response Express-style response
@param {function} next Express-style next callback
350372
function throttleMiddleware (request, response, next) {
    var ip = null

    if (config.useCustomHeader && request.headers[config.useCustomHeader]) {
      ip = request.headers[config.useCustomHeader]
    } else {
      ip = request.headers['x-forwarded-for'] ||
        request.connection.remoteAddress ||
        request.socket.remoteAddress ||
        request.connection.socket.remoteAddress || ''

      ip = ip.split(',')[0]
      if (!ipRegex().test(ip) || ip.substr(0, 7) === '::ffff:' || ip === '::1') {
        ip = '127.0.0.1'
      } else {
        ip = ip.match(ipRegex())[0]
      }
    }

    Throttle
      .findOneAndUpdate({ip: ip}, { $inc: { hits: 1 } }, { upsert: false })
      .exec(function (error, throttle) {
        if (errHandler(response, next, error)) { return }
        if (!throttle) {
          throttle = new Throttle({
            createdAt: new Date(),
            ip: ip
          })
          throttle.save(function (error, throttle) {
            // THERE'S NO ERROR, BUT THROTTLE WAS NOT SAVE
            if (!throttle && !error) {
              error = new Error('Error checking rate limit.')
            }

            if (errHandler(response, next, error)) { return }

            respondWithThrottle(request, response, next, throttle)
          })
        } else {
          respondWithThrottle(request, response, next, throttle)
        }
      })
  }
869177
function(options,done) {

    request(options, function (err, response, payload) {
        if (err) {
            console.log('api call error');
            console.log(err);
        }

        done(err, payload, parseRateLimits(response.headers));
    });
}
839515
function(request, response, next){
		if (!utils.Misc.isNullOrUndefined(request.user) || request.originalUrl == '/error' || request.originalUrl.indexOf('/error?') == 0) {
			next();
		}
		else {
			var success = encodeURIComponent(request.protocol + '://' + request.get('host') + request.originalUrl);
			response.redirect('/login?success=' + success + '&no_query=true'); //we don't want it to add any query string
		}
	}
1122899
function ( req, res, next ) {

    if ( req.body ) {
        trimStringProperties(req.body);
    }

    if ( req.params ) {
        trimStringProperties(req.params);
    }

    if ( req.query ) {
        trimStringProperties(req.query);
    }

    next();

}
256109
function (nextRequest) {
    var exit, target, method;

    while(this._exits.length) {
      exit = this._exits.pop();
      target = exit.target;
      method = exit.method;

      if (!(method in target)) {
        throw new Error("Can't call exit " + method + ' on target when changing uri to ' + request.uri);
      }

      target[method].call(target, nextRequest);
    }
  }
171629
function interceptIndex(request, response, next) {
	if (args.index === true && request.path === '/') {
		request.path = '/index.json';
	}
	return next();
}
414325
function proxyServerMidleware(req, res, next) {
    // Check if static resource exist
    var sfile = path.join(req.app.get('static resource'), req.path);
    if(fs.existsSync(sfile)) {
        return next();
    }
    // Proxy request
    // --------------
    // buffer so that it won't be lost,
    // !!This is confilced with `methodOverride()`
    var buffer = httpProxy.buffer(req);
    var proxySetting = req.app.get('proxy setting');
    // Do process
    ProxyInstance.proxyRequest(req, res, {
        host: proxySetting.remote.host,
        port: proxySetting.remote.port,
        buffer: buffer
    });
}
608094
function next() {
  var limireq = this;
  var conn = limireq.connections.shift()
  if (!conn) return

  request(conn.options, function(err, res, body) {
    if (typeof conn.callback === 'function')
      conn.callback(err, res, body)
    else
      limireq.emit('data', err, res, body)

    // Signal the end of processing
    if (++limireq.completed === limireq.total) {
      limireq.active = false
      limireq.emit('end')
    } else next.call(limireq)
  })
}
637858
function makeHttpRequest(reqHeaders, expectedRes, cacheHitExpected, next) {
  reqHeaders.cookie = _.reduce(reqHeaders.cookie, function(memo, val, name) {
    memo.push(name + '=' + val);
    return memo;
  }, []).join('; ');

  var start = Date.now();

  request({
    url: 'http://localhost:1337',
    method: 'GET',
    headers: reqHeaders
  }, function(err, data, body) {
    var time = Date.now() - start;

    console.log('  status:', data.statusCode);
    console.log('  body  :', body);
    console.log('  time  :', time);

    common.verify(function() {
      JSON.parse(body).should.eql(expectedRes);
      common.shouldUseCache(cacheHitExpected, time);
    });

    next();
  });
}
193676
private Call getNextCall(Integer nextLimit, String continueToken) {
    PagerParams params = new PagerParams((nextLimit != null) ? nextLimit : limit, continueToken);
    return listFunc.apply(params);
  }
1283725
function done( error, response, data ) {
		var info;
		if ( arguments.length === 1 ) {
			debug( 'No available rate limit information.' );
			return clbk( error );
		}
		debug( 'Request completed.' );

		// Get rate limit information:
		info = ratelimit( response.headers );
		debug( 'Rate limit: %d', info.limit );
		debug( 'Rate limit remaining: %d', info.remaining );
		debug( 'Rate limit reset: %s', (new Date( info.reset*1000 )).toISOString() );

		if ( error ) {
			return clbk( error, null, info );
		}
		clbk( null, data, info );
	}
142019
public static RequestLimitingHandler requestLimitingHandler(final int maxRequest, final int queueSize, HttpHandler next) {
        return new RequestLimitingHandler(maxRequest, queueSize, next);
    }
1176402
function onRequest(request, response) {
  if (request.url == "/favicon.ico") {
    var data = getFavIcon()
    if (!data) {
      response.writeHead(404, {"Content-Type": "text/plan"})
      response.end(request.url + " not found")
      return
    }

    response.writeHead(200, {"Content-Type": "image/png"})
    response.end(data)
    return
  }

  response.writeHead(200, {"Content-Type": "text/html"})
  response.end(getOpts.getHelpHTML())
}
884006
function Router(req, res, next) {
        const server = this;
        const state = {
            method: req.method.toUpperCase(),
            params: {},
            routes: routes.concat(),
            routeUnhandled: true,
            server: server,
        };
        run(state, req, res, err => {
            req.params = {};
            if (state.routeUnhandled) req.log('unhandled', 'Router had no matching paths');
            next(err);
        });
    }
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);
      });
    }
  }
50476
function (req, res, next) {
            if (options.forceAuthorize) {
                return next();
            }
            var userId = req.oauth2.user.id;
            var clientId = req.oauth2.client.id;
            var scope = req.oauth2.req.scope;
            models.Permissions.isAuthorized(clientId, userId, scope,
                function (err, authorized) {
                    if (err) {
                        return next(err);
                    } else if (authorized) {
                        req.oauth2.res = {};
                        req.oauth2.res.allow = true;
                        server._respond(req.oauth2, res, function (err) {
                            if (err) {
                                return next(err);
                            }
                            return next(new AuthorizationError('Unsupported response type: '
                                + req.oauth2.req.type, 'unsupported_response_type'));
                        });
                    } else {
                        next();
                    }
                });
        }
46422
function onRequest(context, req, reply, next) {
  const m = context._serverDecoder(context.request.payload)

  if (m.error) {
    next(m.error)
    return
  }

  const msg = m.value

  if (msg) {
    context.meta$ = msg.meta || {}
    context.trace$ = msg.trace || {}
    context.delegate$ = msg.delegate || {}
    context.request$ = msg.request || {}
    context.auth$ = {}
  }

  context.request.payload = m.value
  context.request.error = null

  // incoming pattern
  context._pattern = context.request.payload.pattern

  // find matched action
  context.matchedAction = context._router.lookup(context._pattern)

  // We have to remove the pattern manually when maxMessages$ was received.
  // This is required because NATS unsubscribe events is fired too early.
  // Only relevant for server actions with custom transport options.
  if (context.matchedAction !== null) {
    context.matchedAction[sAddReceivedMsg]++
    if (context.matchedAction[sAddReceivedMsg] === context.matchedAction.transport.maxMessages) {
      // we only need to remove the pattern because the subscription is unsubscribed by nats driver automatically
      context.cleanTopic(context._topic)
    }
  } else if (context._notFoundPattern !== null) {
    // fallback to notFound action when defined
    context.matchedAction = context._router.lookup(context._notFoundPattern)
  }

  if (context._config.traceLog === true) {
    context.log = context.log.child({
      tag: context._config.tag,
      requestId: context.request$.id,
      parentSpanId: context.trace$.parentSpanId,
      traceId: context.trace$.traceId,
      spanId: context.trace$.spanId
    })
    context.log.info(
      {
        pattern: context.trace$.method
      },
      'Request received'
    )
  } else {
    context.log.info(
      {
        requestId: context.request$.id,
        pattern: context.trace$.method
      },
      'Request received'
    )
  }

  next()
}