title: onRequest meta:

  • name: description content: 收到请求事件
  • name: keywords content: swoole|swoole extension|swoole framework|EasySwoole|swoole|onRequest

onRequestEvent

  1. public static function onRequest(Request $request, Response $response): bool

EasySwoole executes this event when it receives any HTTP request. This event can intercept HTTP requests globally。

  1. <?php
  2. public static function onRequest(Request $request, Response $response): bool
  3. {
  4. //It is not recommended to intercept requests here, but to add a controller base class for interception
  5. //If you want to intercept, return false
  6. $code = $request->getRequestParam('code');
  7. if (0/*empty($code)Validation fails*/){
  8. $data = Array(
  9. "code" => Status::CODE_BAD_REQUEST,
  10. "result" => [],
  11. "msg" => 'Validation fails'
  12. );
  13. $response->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  14. $response->withHeader('Content-type', 'application/json;charset=utf-8');
  15. $response->withStatus(Status::CODE_BAD_REQUEST);
  16. return false;
  17. }
  18. return true;
  19. }

::: warning If $response->end() is executed in this event, the request will not enter the route matching phase. :::