Appends a Middleware to the route which is to be executed before the route runs
972759
def middleware(self, args):
        
        if self.url[(len(self.url) - 1)] == (self.url_, self.controller, dict(method=self.method, request_type=self.request_type, middleware=None)):
            self.url.pop()
        self.url.append((self.url_, self.controller, dict(method=self.method, request_type=self.request_type, middleware=args)))
        return self
1020979
function nextMiddleware (factory, mw, info) {
  const {
    resolved,
    index,
    routes,
    middlewares,
    errorMiddleware,
    req,
    res,
    metrics
  } = info

  const local = {
    finished: false,
    timeout: null
  }

  // check if the request has already been resolved
  if (resolved) return

  // get the current middleware
  const current = mw[index]
  const exec = {
    name: current.functionName,
    started: Date.now(),
    ended: null,
    data: null
  }

  metrics.executions.push(exec)

  // create a next method
  const next = data => {
    clearTimeout(local.timeout)
    if (local.finished || info.resolved) return
    local.finished = true

    // add the result
    exec.ended = Date.now()
    exec.data = data

    // allow reroutes to valid named route paths
    if (_.isString(data)) {
      const route = routes[data]
      if (!route) {
        if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
          info.index = 0
          req.error = new Error(`No route found for "${data}"`)
          return nextMiddleware(factory, errorMiddleware, info)
        }
        res.end(data)
      }

      // get the correct route set
      const mwSet = route.type === ERROR_MIDDLEWARE
        ? errorMiddleware
        : middlewares

      // increment the re-route counter, set the index and go
      req.reroutes += 1
      info.index = route.index
      return nextMiddleware(factory, mwSet, info)
    }

    // check for an error passed to the next method and not
    // already in the error middleware chain. if condition met
    // start processing error middleware
    if (data instanceof Error) {
      if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
        info.index = 0
        req.error = data
        return nextMiddleware(factory, errorMiddleware, info)
      }
      res.end(data)
    }

    // check if there is any more middleware in the chain
    // if not, call end to complete the request
   return info.index === mw.length
     ? res.end()
     : nextMiddleware(factory, mw, info)
  }

  // create a timeout for the middleware if timeout > 0
  if (current.timeout > 0) {
    local.timeout = setTimeout(() => {
      local.finished = true
      req.error = new Error(current.functionName
        + ' middleware timed out')

      // add the result
      exec.ended = Date.now()
      exec.data = req.error

      // if already in error middleware and timed out
      // end the entire request, othewise move to error mw
      if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
        info.index = 0
        return nextMiddleware(factory, errorMiddleware, info)
      }
      return res.end()
    }, current.timeout)
  }

  // try to execute the resolver and if unable
  // move to error middleware. if already in error
  // middleware end the request
  try {
    info.index += 1
    current.resolver(req, res, next)
  } catch (err) {
    clearTimeout(local.timeout)
    local.finished = true
    factory.emit(EVENT_ERROR, err)
    req.error = err

    // add the result
    exec.ended = Date.now()
    exec.data = req.error

    if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
      info.index = 0
      return nextMiddleware(factory, errorMiddleware, info)
    }
    return res.end()
  }
}
504754
function route() {
        configure()

        middlewares()

        for (let route of config.routes) {
            if (route.type === 'view')
                server[route.method](route.src, (req, res) => {
                    res.render(`${app.root}/views/${route.dest}.twig`, {})
                })

            if (route.type === 'controller') {
                let [path, method] = route.dest.split('::')

                let controller = function () {
                    if (!app.controllers)
                        return require(`${app.root}/controllers/${path.replace('.', '/')}`)(app)

                    if (path.split('.').length > 1)
                        return app.controllers[path.split('.')[0]][path.split('.')[1]]
                    else
                        return app.controllers[path]
                }()

                let func = wrapper(controller[method])
                if (!func)
                    app.drivers.logger.error('blockbase-express - wrapper', `Undefined function ${controller}${method}`)

                if (route.method === 'post' || route.method === 'put')
                    server[route.method](route.src, upload.any(), func)
                else
                    server[route.method](route.src, func)
            }
        }

        errors()
    }
1190669
def add_route(app, fn, context=default_context):
    
    transmute_func = TransmuteFunction(
        fn,
        args_not_from_request=["request"]
    )
    handler = create_handler(transmute_func, context=context)
    get_swagger_spec(app).add_func(transmute_func, context)

    for p in transmute_func.paths:
        aiohttp_path = _convert_to_aiohttp_path(p)
        resource = app.router.add_resource(aiohttp_path)
        for method in transmute_func.methods:
            resource.add_route(method, handler)
188819
def dispatch(self, operation, request, **path_args):
        
        # Add current operation to the request (for convenience in middleware methods)
        request.current_operation = operation

        try:
            for middleware in self.middleware.pre_request:
                response = middleware(request, path_args)
                # Return HttpResponse if one is returned.
                if isinstance(response, HttpResponse):
                    return response

            response = self._dispatch(operation, request, path_args)

            for middleware in self.middleware.post_request:
                response = middleware(request, response)

        except Exception as ex:
            if self.debug_enabled:
                # If debug is enabled then fallback to the frameworks default
                # error processing, this often provides convenience features
                # to aid in the debugging process.
                raise
            self.handle_500(request, ex)
            return HttpResponse("Error processing response.", HTTPStatus.INTERNAL_SERVER_ERROR)

        else:
            return response
759240
function preBottom(ctx, goToBottomMiddleware) {
      // If no route match or no methods are defined, go to next middleware
      if (node.isGag || !node.methods.size) {
        return next()
      }
      // If there is no one middleware
      // it's a 405 error
      if (!bottom.length) {
        ctx.response.set('Allow', this.methods.toString())
        ctx.response.status = 405
        return
      }

      return goToBottomMiddleware()
    }
609838
function (routerMiddelware, req, res, next) {
		var middlewareFilename = routerMiddelware.split('.')[0];
		var middlewareFunction = routerMiddelware.split('.')[1];

		if (!req.pipa) req.pipa = {};

		this.middlewares[middlewareFilename][middlewareFunction](req, res, function (data) {
			_.extend(req.pipa, data); next();
		});
	}
428263
def make_middleware(self, app):
        

        def application(environ, start_response):
            return ClosingIterator(app(environ, start_response), self.cleanup)

        return application
155280
function (routes) {
		var self = this;

	
		fs.readdirSync(this.middlewareBasePath()).filter(file => file.match(/\.js$/) || file.match(/\.coffee$/)).forEach(function (file) {
			var middlewareName = file.replace(/\.js$/, '').replace(/\.coffee$/, '');
			self.middlewares[middlewareName] = require(path.join(self.middlewareBasePath(), middlewareName));
		});


		for (var root in routes) {
			if (root && routes[root]) {
				for(var key in routes[root]) {
					var method = key.trim().split(' ')[0].toLowerCase();
					var routerMiddelware = routes[root][key];
					var endpoint;

					if (root == 'index') endpoint = ((key.trim().split(' ')[1].toLowerCase() != '/') ? key.trim().split(' ')[1].toLowerCase() : '/');
					else endpoint = '/' + root + ((key.trim().split(' ')[1].toLowerCase() != '/') ? key.trim().split(' ')[1].toLowerCase() : '');

					self.__endpoint__handler(method, endpoint, routerMiddelware);
				}
			}
		}
	}
30172
function compose(middlewares, path) {
    if (!Array.isArray(middlewares)) {
        throw new Error(`middlewares ${JSON.stringify(middlewares)} should be an Array of functions.`);
    }
    if (middlewares.length) {
        for (const fn of middlewares) {
            if (typeof fn !== 'function') {
                throw new Error(`middleware ${path} - ${JSON.stringify(fn)} should be a function, ignored.`);
            }
        }
    }
    return (req, res, next) => {
        (function iterate(i, max) {
            if (i === max) {
                return next();
            }
            middlewares[i](req, res, iterate.bind(this, i + 1, max));
        })(0, middlewares.length);
    }
}
554075
function addStaticRoute(routePath, targets) {
		if (!Object.isArray(targets)) {
			targets = [targets];
		}
		targets.forEach(function(target) {
			if (target)
				app.use(routePath, app.middleware.static(path.resolve(config.rootDir, target)));
		});
	}
1149966
def prepare_middleware(&context_definition)
      last_middleware = AllImportantMiddleware.new(&context_definition)
      Context.middlewares.inject(last_middleware) do |previous_middleware, middleware|
        middleware.new(previous_middleware)
      end.call(self)
    end
1269605
public function appendInit(callable $middleware, $name = null)
    {
        $this->add(self::INIT, $name, $middleware);
    }
622673
function(){
                if (executionChainDone){
                    console.log('execution done !!!')
                    return;
                }
                if (i >= _middleware.length){

                    fn(request,response);
                }
                else{
                    mf = _middleware[i];
                    i++;
                    mf(request,response,next);
                }
            }
450327
public function runBefore() {
        if($this->_beforeController !== null) {
            foreach($this->_beforeController as $hookProvider) {
                $hookProvider->doBefore();
            }
        }
    }
1035167
private static function runAppMiddleware()
    {
        $appMiddleware = Filter::$middleware;

        foreach ($appMiddleware as $middleware) {
            $middleware = instance($middleware);

            $middleware->handle(new Request());
        }

        return true;
    }
1178414
public Blade before(@NonNull String path, @NonNull RouteHandler handler) {
        this.routeMatcher.addRoute(path, handler, HttpMethod.BEFORE);
        return this;
    }