Automatic routing setup
338771
function Routing(app) {
	var config, defaultController;

	/**
	 * Find the action function based on controller name and action name.
	 * If no controller but a model is found, the default controller is taken.
	 * @param  {String} controllerName controller name
	 * @param  {String} actionName     action name
	 * @return {Function}              action function
	 */
	function getAction(controllerName, actionName) {
		controllerName = controllerName.camelize();
		var controller = app.controllers[controllerName];
		if (controller === undefined && app.models[controllerName])
			controller = defaultController;

		if (controller)
			return controller[actionName || 'index'];
		else
			return null;
	}

	/**
	 * adds a single route
	 * @param {String} verb           HTTP verb
	 * @param {String} routePath      routing path
	 * @param {String} controllerName controller name
	 * @param {String} actionName     action name
	 */
	function addSingleRoute(verb, routePath, controllerName, actionName) {
		// add controller and action fields to the request
		var reqExtender = function(req, res, next) {
			req.controller = controllerName;
			req.action = actionName || 'index';
			next();
		};

		var params = [routePath, reqExtender];
		params = params.concat(getPolicies(controllerName, actionName));
		params.push(getAction(controllerName, actionName));

		app[verb].apply(app, params);
	}

	/**
	 * gets the policies in effect for a given controller and action
	 * @param  {String} controller
	 * @param  {String} action
	 * @return {Array}            policies
	 */
	function getPolicies(controller, action) {
		var policies = config.policies;
		var currentPolicies = [];
		if (policies[controller] && policies[controller][action]) {
			currentPolicies = policies[controller][action];
		} else if (Object.isString(policies[controller])) {
			currentPolicies = policies[controller];
		} else if (policies[controller] && policies[controller]['*']) {
			currentPolicies = policies[controller]['*'];
		} else if (policies['*']) {
			currentPolicies = policies['*'];
		}

		if (currentPolicies === true) {
			currentPolicies = [];
		}

		if (!Object.isArray(currentPolicies)) {
			currentPolicies = [currentPolicies];
		}

		currentPolicies = currentPolicies.map(function(policy) {
			var policyPath = path.join(config.rootDir, config.paths.policies, policy);
			return require(policyPath);
		});
		return currentPolicies;
	}

	/**
	 * parse the resource route definitions
	 */
	var resourceRouting;
	function parseResourceRoutes() {
		var routes = config.resourceRouting;
		resourceRouting = [];
		for (var route in routes) {
			var parsedRoute = parseRoute(route, routes[route]);
			// if it's a string it defines the action
			if (Object.isString(parsedRoute.target)) {
				parsedRoute.target = {action: parsedRoute.target};
			}
			resourceRouting.push(parsedRoute);
		}
	}

	/**
	 * add a resource route
	 * @param {String} routePath      route path
	 * @param {String} controllerName controller name
	 */
	function addResourceRoute(routePath, controllerName) {
		resourceRouting.forEach(function(route) {
			var actionPath = route.path.replace(':controller', controllerName);
			route.verbs.forEach(function (verb) {
				addSingleRoute(verb, actionPath, controllerName, route.target.action);
			});
		});
	}

	/**
	 * add a static route
	 * @param {String} routePath route path
	 * @param {String} target    target path (relative to the scarab root)
	 */
	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)));
		});
	}

	function addRedirectRoute(verb, routePath, target) {
		app[verb](routePath, function(req, res) {
			res.redirect(target);
		});
	}

	/**
	 * apply the path policies (for static routes)
	 */
	function applyPathPolicies() {
		var allPolicies = [];
		for (var routePath in config.policies) {
			if (routePath.charAt(0) === '/') {
				var currentPolicies = config.policies[routePath];
				if (currentPolicies === true) {
					currentPolicies = [];
				}
				if (!Object.isArray(currentPolicies)) {
					currentPolicies = [currentPolicies];
				}
				allPolicies.push({route: routePath, policies: currentPolicies});
			}
		}
		allPolicies.forEach(function(pathPolicy) {
			pathPolicy.policies.forEach(function(policy) {
				var policyPath = path.join(config.rootDir, config.paths.policies, policy);
				app.all(pathPolicy.route, require(policyPath));
			});
		});
	}

	/**
	 * parse a route
	 * @param  {String} route  a route definition
	 * @param  {Object} target target definition
	 * @return {Object}        route parsed into verbs, path and target
	 */
	function parseRoute(route, target) {
		var verbs, routePath, routeParts;

		routeParts = route.split(' ');
		if (routeParts.length === 1) {
			verbs = ['all'];
			routePath = routeParts[0];
		} else {
			verbs = routeParts[0].split(',');
			verbs.map(function (verb) {
				return verb.trim().toLowerCase();
			});
			routePath = routeParts[1];
		}
		return {verbs: verbs, path: routePath, target: target};
	}

	/**
	 * initializes all routes
	 */
	function init() {
		config = app.config;

		defaultController = config.defaultControllerFactory(app.models);

		// load controllers
		var controllerDir = path.join(config.rootDir, config.paths.controllers);
		var controllerFiles = fs.readdirSync(controllerDir);
		controllerFiles.forEach(function(controllerFile) {
			var controllerName = controllerFile.substring(0, controllerFile.indexOf('Controller'));
			var controllerDef = require(path.join(controllerDir, controllerFile));
			var controller;
			if (controllerDef.noDefaultActions) {
				controller = controllerDef;
			} else {
				controller = Object.create(defaultController);
				controller = Object.merge(controller, controllerDef);
			}
			app.controllers[controllerName] = controller;
		});

		applyPathPolicies();

		var routes = config.routes,
			parsed = [];

		parseResourceRoutes();

		for (var route in routes) {
			parsed.push(parseRoute(route, routes[route]));
		}

		parsed.forEach(function(route) {
			if(!route.target)
				return;

			if (Object.isString(route.target)) {
				if (route.verbs[0] !== 'static' && route.target.charAt(0) === '/') {
					route.target = {redirect: route.target};
				} else {
					var parts = route.target.split('.');
					if (parts.length === 2) {
						route.target = {controller: parts[0], action: parts[1]};
					}
				}
			}
			if (!Object.isObject(route.target)) {
				route.target = {controller: route.target};
			}

			route.verbs.forEach(function (verb) {
				if (verb === 'resource') {
					addResourceRoute(route.path, route.target.controller);
				} else if (verb === 'static') {
					addStaticRoute(route.path, route.target.controller);
				} else if (route.target.redirect) {
					addRedirectRoute(verb, route.path, route.target.redirect);
				} else {
					addSingleRoute(verb, route.path, route.target.controller, route.target.action);
				}
			});
		});

		if(config.autoRoute) {
			resourceRouting.forEach(function(route) {
				var actionPath = path.join('/', config.autoRoutePath, route.path);
				route.verbs.forEach(function (verb) {
					app[verb](actionPath, function(req, res, next) {
						var controllerName = req.params.controller.singularize();
						var actionName = route.target.action;
						req.controller = controllerName;
						req.action = actionName;

						var action = getAction(controllerName, actionName);
						if (action) {
							var policies = getPolicies(controllerName, actionName);
							if (policies.length > 0) {
								var policyIdx = 0;
								var nextPolicy = function() {
									policyIdx++;
									if (policyIdx < policies.length) {
										policies[policyIdx](req, res, nextPolicy);
									} else {
										action(req, res, next);
									}
								};
								policies[0](req, res, nextPolicy);
							} else {
								action(req, res, next);
							}
						} else {
							next();
						}
					});
				});
			});
		}
	}

	return {
		init: init
	};
}
784102
public function setup()
    {
        $this->groupRoutes();

        foreach ($this->routes as $type => $routes) {
            foreach ($routes as $name => $route) {
                $newRoute = new Route($name, $route);
                if (!$newRoute->hasParam('hostname')) {
                    $newRoute->setParam('hostname', $this->resolveDefaultHostName());
                }

                $routeType = $this->resolveRouteType($type);
                $routeType->add($this->getRouter(), $newRoute);
            }
        }
    }
1163006
public function autodetectProxySettings()
    {
        $wrappers = array('http', 'https', 'ftp');

        foreach ($wrappers as $wrapper) {
            $url = getenv($wrapper.'_proxy');
            if (!empty($url)) {
                $params = array_merge(array(
                    'port'  => null,
                    'user'  => null,
                    'pass'  => null,
                    ), parse_url($url));
                $this->addProxySettings($params['host'], $params['port'], $wrapper, $params['user'], $params['pass']);
            }
        }
    }
680528
def setup(app: Application,
          tracer: Tracer, *,
          skip_routes: Optional[AbstractRoute] = None,
          tracer_key: str = APP_AIOZIPKIN_KEY,
          request_key: str = REQUEST_AIOZIPKIN_KEY) -> Application:
    
    app[tracer_key] = tracer
    m = middleware_maker(skip_routes=skip_routes,
                         tracer_key=tracer_key,
                         request_key=request_key)
    app.middlewares.append(m)

    # register cleanup signal to close zipkin transport connections
    async def close_aiozipkin(app: Application) -> None:
        await app[tracer_key].close()

    app.on_cleanup.append(close_aiozipkin)

    return app
684591
private function runRouteBinding(): void
    {
        // calculated depend of language
        $pathway = $this->getPathInfo();
        /** @var array $routing */
        $routing = App::$Properties->getAll('Routing');

        // try to work with static aliases
        if (Any::isArray($routing) && isset($routing['Alias'], $routing['Alias'][env_name])) {
            $pathway = $this->findStaticAliases($routing['Alias'][env_name], $pathway);
        }

        $this->setPathdata(explode('/', trim($pathway, '/')));

        // set default controller and action for undefined data
        if (!$this->action) {
            $this->action = 'Index';
        }

        // empty or contains backslashes? set to main
        if (!$this->controller || Str::contains('\\', $this->controller)) {
            $this->controller = 'Main';
        }

        // find callback injection in routing configs (calculated in App::run())
        if (Any::isArray($routing) && isset($routing['Callback'], $routing['Callback'][env_name])) {
            $this->findDynamicCallbacks($routing['Callback'][env_name], $this->controller);
        }
    }
1209476
def setup(self):
        """"""

        self.allow = self.config['allow']
        self.halt = self.config['halt']
        self.skip = self.config['skip']
1202383
function(router, pathname, handler, msg_, preMsg, msg2) {

const msg = (msg2 && ` ${msg2}`) || (msg_ && `@${msg_}`) || '';

if (msg) {
  console.log(`${pad(preMsg, 35)} ${lpad(pathname,55)} ${msg}`);
}

  router.addRoute(pathname, function(req, res, params) {

    if (getDumpReqVerbosity() > 0) {
      dumpReq(req, res, `--------vvvvv\n${msg2} handling`, {skipBody:true, verbosity:getDumpReqVerbosity(), postMsg: '------^^^^^'});
    }

    return handler.apply(this, arguments);
  });
}
131284
private function setAccessControllers(): void
    {
        $this->absolutePathToAccessControllers = [];
        $route = $this->routingBasePath;

        foreach ($this->getRealArgs() as $arg)
        {
            $route .= $arg . '/';
            $path = $route . 'access.php';

            if (\is_file($path)) {
                array_unshift($this->absolutePathToAccessControllers, $path);
                break;
            }
        }
    }
283103
def _auto_connect(self):
        """"""
        while not self._teardown.value:
            try:
                self._connect()
                return True
            except exceptions.RoasterLookupError:
                time.sleep(.25)
        return False
670579
protected function setupUrlRouting()
    {
        $rewriter = new Rewriter();
        $rewriter->initialize();

        $router = Router::urlRouting();

        $this->setConfig("runtime.rewriter_reference", $rewriter);
        $this->setConfig("runtime.router_reference", $router);
    }
1204791
def create(name, database=None, auto=False, auto_source=False, directory=None, verbose=None):
    """"""
    router = get_router(directory, database, verbose)
    if auto and auto_source:
        auto = auto_source
    router.create(name, auto=auto)
650521
protected function setup($str_controller, $bol_parse = TRUE)
    {
        $this->str_controller = ($bol_parse ? $this->parseController($str_controller) : $str_controller);
        if (!method_exists($this->str_controller, 'dispatch')) {
            throw new Routing("Could not find controller: {$this->str_controller}");
        }
    }
612727
def auto_discover():
    
    urls = [
        url(r'^admin/', admin.site.urls),
    ]

    # TODO: we can create python package to have a lot of controllers
    # in separate files
    def get_controllers(module_name):
        """Return list of controllers in a module."""
        module = import_module('app.controllers.{}'.format(module_name))
        controllers = []
        for obj_name in dir(module):
            # we ignore import of Controller and hidden names
            if obj_name.startswith('_') or obj_name == 'Controller':
                continue
            obj = getattr(module, obj_name)
            # include only controllers
            if issubclass(obj, Controller):
                controllers.append(obj)
        return controllers

    def controller_to_path(controller):
        """
        Convert controller's name to a valid path.

        Make url in lower case by replace capital letters to small
        and adding underscore between words.
        """
        words = re.findall('[A-Z][a-z]*', controller.__name__)
        if words[-1] == 'Controller':
            del words[-1]
        # transform words to a url address
        url_path = '_'.join(words).lower()
        # main controller is a root handler
        # TODO: root address inside the file should always come last
        if url_path == 'main':
            url_path = ''
        return url_path

    # load all controllers (excluding main controllers)
    for file_name in listdir('controllers', get_files=True, hide_ignored=True):
        # remove .py extension from file name
        app_name = file_name.split('.', 1)[0]
        # we will include main controller at the end
        if app_name == 'main':
            continue
        # add url for each controller
        for controller in get_controllers(app_name):
            url_path = controller_to_path(controller)
            urls.append(url(
                r'^{}/{}$'.format(app_name, url_path),
                controller.as_view()
            ))

    # add urls for main controllers
    for controller in get_controllers('main'):
        url_path = controller_to_path(controller)
        # map urls to a root path
        urls.append(url(
            r'^{}$'.format(url_path),
            controller.as_view()
        ))

    return urls
965661
def make_router(self, rule, method=None, handler=None, cls=None,
                    name=None, **params):
        '''
        '''
        cls = cls or Router
        router = cls(rule, name=name, **params)
        for r in self.routes:
            if r._route == router._route:
                if isinstance(r, cls):
                    router = r
                    router._set_params(params)
                    break
        if method and handler:
            if isinstance(method, tuple):
                for m in method:
                    setattr(router, m, handler)
            else:
                setattr(router, method, handler)
        return router
365843
protected function mapWebRoutes(): void
    {
        $file = $this->basePath.'routes/web.php';

        if (file_exists($file)) {
            $this->loadRoutesFrom(
                Route::middleware('web')
                ->group($file));
        }
    }
243410
def cli(env):
    """"""
    mgr = SoftLayer.LoadBalancerManager(env.client)

    routing_types = mgr.get_routing_types()
    table = formatting.KeyValueTable(['ID', 'Name'])
    table.align['ID'] = 'l'
    table.align['Name'] = 'l'
    table.sortby = 'ID'
    for routing_type in routing_types:
        table.add_row([routing_type['id'], routing_type['name']])
    env.fout(table)
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()
    }