Middleware: 请求超时

请求超时控制也是不可或缺的中间件:

  1. <?php
  2. class RequestTimeout implements Middleware
  3. {
  4. public $timeout;
  5. public $exception;
  6. private $timerId;
  7. public function __construct($timeout, \Exception $ex = null)
  8. {
  9. $this->timeout = $timeout;
  10. if ($ex === null) {
  11. $this->exception = new HttpException(408, "Request timeout");
  12. } else {
  13. $this->exception = $ex;
  14. }
  15. }
  16. public function __invoke(Context $ctx, $next)
  17. {
  18. yield race([
  19. callcc(function($k) {
  20. $this->timerId = swoole_timer_after($this->timeout, function() use($k) {
  21. $k(null, $this->exception);
  22. });
  23. }),
  24. function() use ($next){
  25. yield $next;
  26. if (swoole_timer_exists($this->timerId)) {
  27. swoole_timer_clear($this->timerId);
  28. }
  29. },
  30. ]);
  31. }
  32. }
  33. $app->υse(new RequestTimeout(2000));

也可以结合FastRoute构造出一个按路由匹配请求超时的中间件,留给读者自行实现。