header('Accept'); $contentType = $httpRequest->header('Content-Type'); $ContentTypeBase64 = $httpRequest->header('Content-Type-Base64', 0); $ContentTypeBin = $httpRequest->header('Content-Type-Bin', 0); $forceJson = $httpRequest->header('Force-Json', 0); // 记录响应信息,便于调试 \Illuminate\Support\Facades\Log::debug('Proto响应信息', [ 'Accept' => $acceptHeader, 'Content-Type' => $contentType, 'Content-Type-Base64' => $ContentTypeBase64, 'Content-Type-Bin' => $ContentTypeBin, 'Force-Json' => $forceJson, 'response_size' => strlen($response->serializeToString()), 'response_json_size' => strlen($response->serializeToJsonString()) ]); \Illuminate\Support\Facades\Log::debug('Proto响应信息-json', json_decode($response->serializeToJsonString(),true)); // 强制返回JSON格式(用于调试或客户端不支持二进制解析时) if ($forceJson) { return response()->json( self::protobufToArray($response) )->header('Content-Type', 'application/json'); } // 返回Base64编码的Protobuf数据 if ($ContentTypeBase64) { $base64Data = base64_encode($response->serializeToString()); return response($base64Data) ->header('Content-Type', 'text/plain'); } // 返回JSON格式(当客户端请求JSON或发送JSON请求时) if ($ContentTypeBin == 0) { if (stripos($acceptHeader, 'json') !== false || stripos($contentType, 'json') !== false) { return response()->json( self::protobufToArray($response) ); } } // 返回二进制Protobuf格式(默认) $binaryData = $response->serializeToString(); return response($binaryData) ->header('Content-Type', 'application/x-protobuf'); } /** * 将 Protobuf 消息对象转换为数组 * @param Message $message Protobuf 消息对象 * @return array */ protected static function protobufToArray(Message $message): array { $json = $message->serializeToJsonString(); return json_decode($json, true); } }