在easySwoole群中看到有人想实现强制路由,之前我通过修改核心代码实现,侵入性太强,决定修改成全局拦截实现。

  • 首先定义强制路由配置
    'ROUTE'=>[
        'need'=>true,
    ],
  • 将以下代码写在根目录的EasySwooleEvent.php文件,onRequest方法中即可
        $class = 'App\\HttpController\\Router'; //根据实际路由命名空间设置
        $router = class_exists($class) ? new $class : null;
        $routeConfig = Config::getInstance()->getConf('ROUTE'); //读取配置文件
        //如果配置为true且路由未实现则拦截
        if ($routeConfig['need'] === true && !($router instanceof Router)) {
            Trigger::error('Router Class Not Found');
            $response->withStatus(Status::CODE_NOT_FOUND);
            $response->end();
        }
        if ($router instanceof Router) {
            //获取路由分发信息,失败则拦截
            $routerDispatcher = new GroupCountBased($router->getRouteCollector()->getData());
            $routeInfo = $routerDispatcher->dispatch($request->getMethod(), UrlParser::pathInfo($request->getUri()->getPath()));
            if ($routeInfo !== false) {
                if ($routeConfig['need'] === true && $routeInfo[0] === 0) {
                    Trigger::error('Router Not Found');
                    $response->withStatus(Status::CODE_NOT_FOUND);
                    $response->end();
                }
            }
        }