parse static method

HttpResponse parse(
  1. Uint8List data
)

Parse response from wire format

Implementation

static HttpResponse parse(Uint8List data) {
  final dataString = utf8.decode(data);
  final headerEndIndex = dataString.indexOf(HttpProtocolConstants.headerSeparator);

  if (headerEndIndex == -1) {
    throw FormatException('Invalid HTTP response: no header separator found');
  }

  final headerSection = dataString.substring(0, headerEndIndex);
  final lines = headerSection.split(HttpProtocolConstants.crlf);

  if (lines.isEmpty) {
    throw FormatException('Invalid HTTP response: no status line');
  }

  // Parse status line
  final statusLine = lines[0].split(' ');
  if (statusLine.length < 3) {
    throw FormatException('Invalid HTTP status line: ${lines[0]}');
  }

  final version = statusLine[0];
  final statusCode = int.tryParse(statusLine[1]);
  if (statusCode == null) {
    throw FormatException('Invalid HTTP status code: ${statusLine[1]}');
  }

  final status = HttpStatus.fromCode(statusCode);

  // Parse headers
  final headers = <String, String>{};
  for (int i = 1; i < lines.length; i++) {
    final line = lines[i];
    if (line.isEmpty) continue;

    final colonIndex = line.indexOf(':');
    if (colonIndex == -1) {
      throw FormatException('Invalid HTTP header: $line');
    }

    final key = line.substring(0, colonIndex).trim().toLowerCase();
    final value = line.substring(colonIndex + 1).trim();
    headers[key] = value;
  }

  // Extract body if present
  Uint8List? body;
  final bodyStartIndex = headerEndIndex + HttpProtocolConstants.headerSeparator.length;
  if (bodyStartIndex < data.length) {
    body = data.sublist(bodyStartIndex);
  }

  return HttpResponse(
    status: status,
    version: version,
    headers: headers,
    body: body,
  );
}