withHeader('Server', env('RESPONSE_SERVER_NAME', 'Hyperf')); } /** * Transfer the non-standard response content to a standard response object. * * @param null|array|Arrayable|Jsonable|string $response */ protected function transferToResponse($response, ServerRequestInterface $request): ResponseInterface { // 加入Responsable钩子. if ($response instanceof Responsable) { $response = $response->toResponse($request); } if (is_string($response)) { return $this->response()->withAddedHeader('content-type', 'text/plain')->withBody(new SwooleStream($response)); } if (is_array($response) || $response instanceof Arrayable) { return $this->response() ->withAddedHeader('content-type', 'application/json') ->withBody(new SwooleStream(Json::encode($response))); } if ($response instanceof Jsonable) { return $this->response() ->withAddedHeader('content-type', 'application/json') ->withBody(new SwooleStream((string) $response)); } return $response; // return $this->response()->withAddedHeader('content-type', 'text/plain')->withBody(new SwooleStream((string) $response)); } /** * Handle the response when cannot found any routes. * * @param ServerRequestInterface $request * @return array|Arrayable|mixed|ResponseInterface|string */ protected function handleNotFound(ServerRequestInterface $request) { // 重写路由找不到的处理逻辑. $statusCode = 404; $clientRequest = request(); $headerContentType = $clientRequest->header('content-type'); if (!empty($headerContentType) && Str::contains($headerContentType, ['/json', '+json'])) { $res = [ 'code' => $statusCode, 'message' => '404 not found', 'data' => [], 'handshake' => CommonConstant::HANDSHAKE, ]; return $this->response()->withStatus($statusCode)->withAddedHeader('content-type', 'application/json') ->withBody(new SwooleStream(Json::encode($res))); } else { return $this->response()->withStatus($statusCode)->withBody(new SwooleStream((string)$statusCode)); } } /** * Handle the response when the routes found but doesn't match any available methods. * * @return array|Arrayable|mixed|ResponseInterface|string */ protected function handleMethodNotAllowed(array $methods, ServerRequestInterface $request) { // 重写 HTTP 方法不允许的处理逻辑. $statusCode = 405; $clientRequest = request(); $headerContentType = $clientRequest->header('content-type'); if (!empty($headerContentType) && Str::contains($headerContentType, ['/json', '+json'])) { // 重写路由找不到的处理逻辑. $res = [ 'code' => $statusCode, 'message' => '405 Method Not Allowed', 'data' => [], 'handshake' => CommonConstant::HANDSHAKE, ]; return $this->response()->withStatus($statusCode)->withAddedHeader('content-type', 'application/json') ->withBody(new SwooleStream(Json::encode($res))); } else { return $this->response()->withStatus($statusCode)->withAddedHeader('Allow', implode(', ', $methods))->withBody(new SwooleStream((string)$statusCode)); } } }