parse static method
Parse request from wire format
Implementation
static HttpRequest parse(Uint8List data, PeerId remotePeer) {
final dataString = utf8.decode(data);
final headerEndIndex = dataString.indexOf(HttpProtocolConstants.headerSeparator);
if (headerEndIndex == -1) {
throw FormatException('Invalid HTTP request: no header separator found');
}
final headerSection = dataString.substring(0, headerEndIndex);
final lines = headerSection.split(HttpProtocolConstants.crlf);
if (lines.isEmpty) {
throw FormatException('Invalid HTTP request: no request line');
}
// Parse request line
final requestLine = lines[0].split(' ');
if (requestLine.length != 3) {
throw FormatException('Invalid HTTP request line: ${lines[0]}');
}
final method = HttpMethod.fromString(requestLine[0]);
final path = requestLine[1];
final version = requestLine[2];
// 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 HttpRequest(
method: method,
path: path,
version: version,
headers: headers,
body: body,
remotePeer: remotePeer,
);
}