InteractsWithHttp.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. <?php
  2. namespace think\swoole\concerns;
  3. use Swoole\Http\Request;
  4. use Swoole\Http\Response;
  5. use Swoole\Server;
  6. use Symfony\Component\VarDumper\VarDumper;
  7. use think\App;
  8. use think\Container;
  9. use think\Cookie;
  10. use think\Event;
  11. use think\exception\Handle;
  12. use think\Http;
  13. use think\Middleware;
  14. use think\swoole\middleware\ResetVarDumper;
  15. use Throwable;
  16. /**
  17. * Trait InteractsWithHttp
  18. * @package think\swoole\concerns
  19. * @property App $app
  20. * @property Container $container
  21. * @method Server getServer()
  22. */
  23. trait InteractsWithHttp
  24. {
  25. public static $statusTexts = [
  26. 100 => 'Continue',
  27. 101 => 'Switching Protocols',
  28. 102 => 'Processing', // RFC2518
  29. 103 => 'Early Hints',
  30. 200 => 'OK',
  31. 201 => 'Created',
  32. 202 => 'Accepted',
  33. 203 => 'Non-Authoritative Information',
  34. 204 => 'No Content',
  35. 205 => 'Reset Content',
  36. 206 => 'Partial Content',
  37. 207 => 'Multi-Status', // RFC4918
  38. 208 => 'Already Reported', // RFC5842
  39. 226 => 'IM Used', // RFC3229
  40. 300 => 'Multiple Choices',
  41. 301 => 'Moved Permanently',
  42. 302 => 'Found',
  43. 303 => 'See Other',
  44. 304 => 'Not Modified',
  45. 305 => 'Use Proxy',
  46. 307 => 'Temporary Redirect',
  47. 308 => 'Permanent Redirect', // RFC7238
  48. 400 => 'Bad Request',
  49. 401 => 'Unauthorized',
  50. 402 => 'Payment Required',
  51. 403 => 'Forbidden',
  52. 404 => 'Not Found',
  53. 405 => 'Method Not Allowed',
  54. 406 => 'Not Acceptable',
  55. 407 => 'Proxy Authentication Required',
  56. 408 => 'Request Timeout',
  57. 409 => 'Conflict',
  58. 410 => 'Gone',
  59. 411 => 'Length Required',
  60. 412 => 'Precondition Failed',
  61. 413 => 'Payload Too Large',
  62. 414 => 'URI Too Long',
  63. 415 => 'Unsupported Media Type',
  64. 416 => 'Range Not Satisfiable',
  65. 417 => 'Expectation Failed',
  66. 418 => 'I\'m a teapot', // RFC2324
  67. 421 => 'Misdirected Request', // RFC7540
  68. 422 => 'Unprocessable Entity', // RFC4918
  69. 423 => 'Locked', // RFC4918
  70. 424 => 'Failed Dependency', // RFC4918
  71. 425 => 'Too Early', // RFC-ietf-httpbis-replay-04
  72. 426 => 'Upgrade Required', // RFC2817
  73. 428 => 'Precondition Required', // RFC6585
  74. 429 => 'Too Many Requests', // RFC6585
  75. 431 => 'Request Header Fields Too Large', // RFC6585
  76. 449 => 'Retry With',
  77. 451 => 'Unavailable For Legal Reasons', // RFC7725
  78. 500 => 'Internal Server Error',
  79. 501 => 'Not Implemented',
  80. 502 => 'Bad Gateway',
  81. 503 => 'Service Unavailable',
  82. 504 => 'Gateway Timeout',
  83. 505 => 'HTTP Version Not Supported',
  84. 506 => 'Variant Also Negotiates', // RFC2295
  85. 507 => 'Insufficient Storage', // RFC4918
  86. 508 => 'Loop Detected', // RFC5842
  87. 510 => 'Not Extended', // RFC2774
  88. 511 => 'Network Authentication Required', // RFC6585
  89. ];
  90. /**
  91. * "onRequest" listener.
  92. *
  93. * @param Request $req
  94. * @param Response $res
  95. */
  96. public function onRequest($req, $res)
  97. {
  98. $this->waitCoordinator('workerStart');
  99. $args = func_get_args();
  100. $this->runInSandbox(function (Http $http, Event $event, App $app, Middleware $middleware) use ($args, $req, $res) {
  101. $event->trigger('swoole.request', $args);
  102. //兼容var-dumper
  103. if (class_exists(VarDumper::class)) {
  104. $middleware->add(ResetVarDumper::class);
  105. }
  106. $request = $this->prepareRequest($req);
  107. try {
  108. $response = $this->handleRequest($http, $request);
  109. } catch (Throwable $e) {
  110. $response = $this->app
  111. ->make(Handle::class)
  112. ->render($request, $e);
  113. }
  114. $this->sendResponse($res, $response, $app->cookie);
  115. });
  116. }
  117. protected function handleRequest(Http $http, $request)
  118. {
  119. $level = ob_get_level();
  120. ob_start();
  121. $response = $http->run($request);
  122. $content = $response->getContent();
  123. if (ob_get_level() == 0) {
  124. ob_start();
  125. }
  126. $http->end($response);
  127. if (ob_get_length() > 0) {
  128. $response->content(ob_get_contents() . $content);
  129. }
  130. while (ob_get_level() > $level) {
  131. ob_end_clean();
  132. }
  133. return $response;
  134. }
  135. protected function prepareRequest(Request $req)
  136. {
  137. $header = $req->header ?: [];
  138. $server = $req->server ?: [];
  139. foreach ($header as $key => $value) {
  140. $server["http_" . str_replace('-', '_', $key)] = $value;
  141. }
  142. // 重新实例化请求对象 处理swoole请求数据
  143. /** @var \think\Request $request */
  144. $request = $this->app->make('request', [], true);
  145. return $request->withHeader($header)
  146. ->withServer($server)
  147. ->withGet($req->get ?: [])
  148. ->withPost($req->post ?: [])
  149. ->withCookie($req->cookie ?: [])
  150. ->withFiles($req->files ?: [])
  151. ->withInput($req->rawContent())
  152. ->setBaseUrl($req->server['request_uri'])
  153. ->setUrl($req->server['request_uri'] . (!empty($req->server['query_string']) ? '?' . $req->server['query_string'] : ''))
  154. ->setPathinfo(ltrim($req->server['path_info'], '/'));
  155. }
  156. protected function sendResponse(Response $res, \think\Response $response, Cookie $cookie)
  157. {
  158. // 发送Header
  159. foreach ($response->getHeader() as $key => $val) {
  160. $res->header($key, $val);
  161. }
  162. // 发送状态码
  163. $code = $response->getCode();
  164. $res->status($code, isset(self::$statusTexts[$code]) ? self::$statusTexts[$code] : 'unknown status');
  165. foreach ($cookie->getCookie() as $name => $val) {
  166. [$value, $expire, $option] = $val;
  167. $res->cookie($name, $value, $expire, $option['path'], $option['domain'], $option['secure'] ? true : false, $option['httponly'] ? true : false, $option['samesite']);
  168. }
  169. $content = $response->getContent();
  170. $this->sendByChunk($res, $content);
  171. }
  172. protected function sendByChunk(Response $res, $content)
  173. {
  174. $contentSize = \strlen($content);
  175. $chunkSize = 8192;
  176. if ($contentSize > $chunkSize) {
  177. $sendSize = 0;
  178. do {
  179. if (!$res->write(\substr($content, $sendSize, $chunkSize))) {
  180. break;
  181. }
  182. } while (($sendSize += $chunkSize) < $contentSize);
  183. $res->end();
  184. } else {
  185. $res->end($content);
  186. }
  187. }
  188. }