protected function checkParameters(array $parameters, array $options) { try { (new \Owl\Parameter\Validator())->execute($parameters, $options); } catch (\Owl\Parameter\Exception $exception) { throw \Owl\Http\Exception::factory(400, $exception); } }
/** * 去掉路径内的base_path * * @param string $path * @return string */ protected function trimBasePath($path) { $base_path = $this->getConfig('base_path'); if (!$base_path || $base_path === '/') { return $path; } if (stripos($path, $base_path) !== 0) { throw \Owl\Http\Exception::factory(404); } return '/' . substr($path, strlen($base_path)); }
/** * 响应请求,依次执行添加的中间件逻辑. * * @param \Owl\Http\Request $request * @param \Owl\Http\Response $response */ public function execute(\Owl\Http\Request $request, \Owl\Http\Response $response) { $exception_handler = $this->getExceptionHandler(); $method = $request->getMethod(); try { if (!in_array($method, ['HEAD', 'OPTIONS', 'GET', 'POST', 'PUT', 'DELETE', 'PATCH'])) { throw \Owl\Http\Exception::factory(501); } $this->middleware->execute([$request, $response]); } catch (\Exception $exception) { call_user_func($exception_handler, $exception, $request, $response); } catch (\Throwable $error) { call_user_func($exception_handler, $error, $request, $response); } if (!TEST) { $response->end(); } if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); } }
require __DIR__ . '/../src/autoload.php'; $ip = '127.0.0.1'; $port = 12345; $app = new \Owl\Swoole\Application($ip, $port); $app->middleware(function ($request, $response) { $start = microtime(true); (yield true); $use_time = (microtime(true) - $start) * 1000; $response->setHeader('use-time', (int) $use_time . 'ms'); }); $app->middleware(function ($request, $response) { if ($request->getRequestPath() === '/') { $response->setBody('hello world!'); } else { throw \Owl\Http\Exception::factory(404); } (yield true); }); $app->setExceptionHandler(function ($exception, $request, $response) { if ($exception instanceof \Owl\Http\Exception) { $status = $exception->getCode(); $message = $exception->getMessage(); } else { $status = 500; $message = \Owl\Http::getStatusMessage(500); } $response->setStatus($status); $response->setBody($message); }); echo sprintf("Listening http://%s:%d ...\n", $ip, $port);