Route the request object to the right handler function
770753
def route_request(self, request_json, metadata=None):

        '''  '''
        request = Request(request_json)
        request.metadata = metadata
        # add reprompt handler or some such for default?
        handler_fn = self._handlers[self._default] # Set default handling for noisy requests

        if not request.is_intent() and (request.request_type() in self._handlers):
            '''  Route request to a non intent handler '''
            handler_fn = self._handlers[request.request_type()]

        elif request.is_intent() and request.intent_name() in self._handlers['IntentRequest']:
            ''' Route to right intent handler '''
            handler_fn = self._handlers['IntentRequest'][request.intent_name()]

        response = handler_fn(request)
        response.set_session(request.session)
        return response.to_json()
83042
function processHandler(fn) {
                if (_.isFunction(handler)) {
                    return fn(null, handler);
                }
                if (_.isString(handler)) {
                    return self.processStringHandler(mycro, handler, fn);
                }
                if (_.isObject(handler)) {
                    // make sure the object defines a `handler` attribute
                    if (!handler.handler) {
                        return fn('Unable to locate handler for ' + verb.toUpperCase() + ' ' + path.toString());
                    }
                    // extend options with any route specific options
                    if (handler.options && _.isObject(handler.options)) {
                        _.extend(options.defaultOptions, handler.options);
                    }
                    // allow route to override policy chain
                    if (handler.policies && _.isArray(handler.policies)) {
                        options.defaultPolicies = handler.policies;
                    }
                    // allow route to augment policy chain
                    if (handler.additionalPolicies && _.isArray(handler.additionalPolicies)) {
                        options.defaultPolicies = options.defaultPolicies.concat(handler.additionalPolicies);
                    }
                    if (_.isFunction(handler.handler)) {
                        return fn(null, handler.handler);
                    }
                    if (_.isString(handler.handler)) {
                        return self.processStringHandler(mycro, handler.handler, fn);
                    }
                }
                return fn('Unsupported handler type for '+ verb.toUpperCase() + ' ' + path.toString());
            }
1049695
public function process(Request $request, Handler $handler): Response
    {
        $method = $request->getMethod();
        $uri = $request->getUri()->getPath() ?: '/';

        $routeInfo = $this->getDispatcher()->dispatch($method, $uri);

        switch ($routeInfo[0]) {
            case Dispatcher::NOT_FOUND:
                throw new RouteNotFoundException($uri);
            case Dispatcher::METHOD_NOT_ALLOWED:
                throw new MethodNotAllowedException($method);
            case Dispatcher::FOUND:
                $handler = $routeInfo[1];
                $parameters = $routeInfo[2];

                return $handler($request, $parameters);
        }
    }
829442
public static function dispatch()
    {

        $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $method = $_SERVER['REQUEST_METHOD'];

        $searches = array_keys(static::$patterns);
        $replaces = array_values(static::$patterns);

        self::$routes = str_replace('//', '/', self::$routes);

        $foundRoute = false;

        // Parse query parameters
        {
            $query = '';
            $q_arr = array();
            if (strpos($uri, '&') > 0) {
                $query = substr($uri, strpos($uri, '&') + 1);
                $uri = substr($uri, 0, strpos($uri, '&'));
                $q_arr = explode('&', $query);
                foreach ($q_arr as $q) {
                    $qobj = explode('=', $q);
                    $q_arr[] = array($qobj[0] => $qobj[1]);
                    if (!isset($_GET[$qobj[0]])) {
                        $_GET[$qobj[0]] = $qobj[1];
                    }
                }
            }
        }

        // Check if route is defined without regex

        if (in_array($uri, self::$routes)) {

            $routePos = array_keys(self::$routes, $uri);

            // Foreach route position
            foreach ($routePos as $route) {

                if (self::$methods[$route] == $method || self::$methods[$route] == 'ANY') {
                    $foundRoute = true;

                    // If route is not an object

                    if (!is_object(self::$callbacks[$route])) {

                        // Call object controller and method

                        self::invokeObject(self::$callbacks[$route]);
                        if (self::$halts) return;

                    } else {

                        // Call closure

                        call_user_func(self::$callbacks[$route]);
                        if (self::$halts) return;

                    }
                }

            }

        } else {

            // Check if defined with regex
            $pos = 0;

            // Foreach routes

            foreach (self::$routes as $route) {

                $route = str_replace('//', '/', $route);

                if (strpos($route, ':') !== false) {
                    $route = str_replace($searches, $replaces, $route);
                }

                if (preg_match('#^' . $route . '$#', $uri, $matched)) {

                    if (self::$methods[$pos] == $method || self::$methods[$pos] == 'ANY') {
                        $foundRoute = true;

                        // Remove $matched[0] as [1] is the first parameter.

                        array_shift($matched);

                        if (!is_object(self::$callbacks[$pos])) {

                            // Call object controller and method

                            self::invokeObject(self::$callbacks[$pos], $matched);
                            if (self::$halts) return;

                        } else {

                            // Call closure
                            call_user_func_array(self::$callbacks[$pos], $matched);
                            if (self::$halts) return;

                        }
                    }
                }

                $pos++;
            }
        }

        // Run the error callback if the route was not found

        if (!$foundRoute) {

            if (!self::$errorCallback) {

                self::$errorCallback = function () {
                    header($_SERVER['SERVER_PROTOCOL'] . " 404 Not Found");
                    echo '404';
                };
            }

            if (!is_object(self::$errorCallback)) {

                // Call object controller and method
                self::invokeObject(self::$errorCallback, null, 'No routes found.');
                if (self::$halts) return;

            } else {

                call_user_func(self::$errorCallback);
                if (self::$halts) return;

            }
        }
    }
1282508
function Route(method, route, fn) {
    this.method = method;
    this.route = route;
    this.fn = fn;

    return function (app) {
        var middleware = exports.isAppSettingsRoute(route) ? utils.getSettingsMiddlewares() :
            utils.getRequestMiddlewares();

        if (method == "get") {
            app.get(route, middleware, fn)
        }
        else if (method == "post") {
            app.post(route, middleware, fn);
        }
//        var methodRoutes = app.routes[method];
//        return methodRoutes[methodRoutes.length - 1];
    };
}
718695
function requestFilter() {
  return function(req, res, next) {
    if (!_isJsonRequest(req) && !_isVoidFilterRoute(req)) {
      return _renderAppShell(res);
    }
    next();
  };
}
1281967
function Router_process(method, parsedUrl, headers) {

        return this.parseRequest(method, parsedUrl, headers)
            .then(function (routeRule) {
                if (Type.isArray(routeRule) && routeRule.length === 2) {
                    return Promise.resolve(routeRule);
                }
                // only on not found throw an error 404
                throw new error.HttpError(404, core.toObject(routeRule), 'Not found');
            }, function (e) {
                throw new error.HttpError(500, {}, 'Not found', e);
            });
    }
954051
function handleQueryParameters(request, response, next) {
	if (args.query === true && Object.keys(request.query).length > 0) {
		request.path += '/' + Object.keys(request.query).join('_') + '.json';
	}
	return next();
}
1281776
function handleRequest(middleware, handlers, mode, checkArity, req, res, errorHandler) {
  const done = err => err && setImmediate(errorHandler, err, req, res);
  // run global middleware first, then start handling request
  // this is important to allow loggers for example to kick-in regardless
  runMiddlewareStack(middleware, req, res, (err) => {
    if (err) {
      done(err);
      return;
    }
    // try to apply supplied handlers to the requested operation
    handleOperation(handlers, mode, checkArity, req, res, done);
  });
}
1087137
def add_request_handlers_object(self, rh_obj):
        
        rh_dict = {}
        for name in dir(rh_obj):
            if not callable(getattr(rh_obj, name)):
                continue
            if name.startswith("request_"):
                request_name = convert_method_name("request_", name)
                req_meth = getattr(rh_obj, name)
                rh_dict[request_name] = req_meth

        self.add_request_handlers_dict(rh_dict)
1043621
function invokeHTTPHandler(handler, args, req, res, done) {
  // inject parsed parameters into request
  req.params = args;
  // call handler with typical HTTP request/response parameters
  let result = handler(req, res);
  // handle results that are not a trusted Promise with Promise.resolve()
  // which also supports other then-ables
  if (result instanceof Promise === false) {
    result = Promise.resolve(result);
  }
  return result.then(() => done()).catch(done);
}
257932
function router(rpc, handlers, req, res) {
  var $       = rpc.$;
  var api     = rpc.api;
  var request = api.handle(req.method, req.url);
  var dom     = domain.create();

  // the request handler doesn't exit
  // TODO: hoist response logic
  if (!request) {
    res.statusCode = 404;
    res.end();
    return;
  }

  var context = new Context(); // TODO: hoist to own module
  var handle  = request.handle;
  var params  = {};

  // TODO: hoist logic to 'union' module
  var key;
  for(key in request.params) params[key] = request.params[key];
  for(key in request.query)  params[key] = request.query[key];

  var future = $.future();

  future.setWritable(res);
  future.setReadable(req);

  // TODO: extract request making logic
  res.setHeader('Transfer-Encoding' , 'chunked');
  res.setHeader('Content-Type'      , 'application/json');

  dom.on('error', function (err) {
    var statusCode = err.statusCode;

    // only catch known errors, re-throw unexpected errors
    if (!statusCode) throw err;

    // TODO: hoist response logic
    res.statusCode = statusCode;
    res.write(JSON.stringify(err));
    res.end();
  });

  // domain should handle all route errors
  dom.run(function () {
    handlers[handle](future, params, context);
  });
}
237071
function defineRoute (server, opts) {

    server.route({
        method: 'GET',
        path: '/' + opts.plural,
        handler: handler,
        config: {
            jsonp: 'callback',
            validate: {
                query: {},
                payload: false
            }
        }
    });

    function handler (req) {
        var res = {};
        res[opts.plural] = opts.things;
        req.reply(res);
    }

}
174612
def process_request
      verb = request.request_method
      path = request.path

      # In RackStep, each request is processed by a controller. The router
      # is responsable to find, based on the given path and http verb,
      # the apropriate controller to handle the request.
      route = router.find_route_for(path, verb)
      # Initialize the correspondent controller.
      controller = route.controller.new
      # Inject the request into the controller.
      controller.request = request
      # Execute the before method of this controller.
      controller.send(:before)
      # Execute the apropriate method/action.
      controller.send(:process_request)
      # Execute the after method of this controller.
      controller.send(:after)
      # Get from the controller what is the response for this request.
      response = controller.response

      return response
    end
624490
def route(*args, response_formatter=jsonify, **kwargs):
    

    def decorator(func):
        @app.route(*args, **kwargs)
        @functools.wraps(func)
        def wrapped_view(*a, **kw):
            annotations = getattr(func, "__annotations__", {})
            reqargs = {
                name: value
                for name, value in annotations.items()
                if isinstance(value, fields.Field) and name != "return"
            }
            response_schema = annotations.get("return")
            parsed = parser.parse(reqargs, request)
            kw.update(parsed)
            response_data = func(*a, **kw)
            if response_schema:
                return response_formatter(response_schema.dump(response_data).data)
            else:
                return response_formatter(func(*a, **kw))

        return wrapped_view

    return decorator
1258715
def handle(self):
        """"""
        rv = None
        try:
            rv = BaseHTTPRequestHandler.handle(self)
        except (_ConnectionError, socket.timeout) as e:
            self.connection_dropped(e)
        except Exception as e:
            if self.server.ssl_context is None or not is_ssl_error(e):
                raise
        if self.server.shutdown_signal:
            self.initiate_shutdown()
        return rv
188118
function handleRoute(seneca, options, request, reply, route, next) {
  if (options.parseBody) {
    return ReadBody(request, finish)
  }
  finish(null, request.body || {})

  // Express requires a body parser to work in production
  // This util creates a body obj without neededing a parser
  // but doesn't impact loading one in.
  function finish(err, body) {
    if (err) {
      return next(err)
    }

    // This is what the seneca handler will get
    // Note! request$ and response$ will be stripped
    // if the message is sent over transport.
    const payload = {
      request$: request,
      response$: reply,
      args: {
        body: body,
        route: route,
        params: request.params,
        query: request.query,
        user: request.user || null
      }
    }

    // Call the seneca action specified in the config
    seneca.act(route.pattern, payload, (err, response) => {
      if (err) {
        return next(err)
      }

      // Redirect or reply depending on config.
      if (route.redirect) {
        return reply.redirect(route.redirect)
      }
      if (route.autoreply) {
        return reply.send(response)
      }
    })
  }
}