toWebResponse function
Converts an Aim Response into a web.Response.
Set-Cookie values joined with \n become separate headers. Bodies are
streamed through a ReadableStream so SSE and large responses flow
chunk by chunk. An empty body, or a status for which the Fetch spec
forbids a body (101, 204, 205, 304), is sent as null; in the latter
case the Dart body is still drained so any stream producer completes.
Implementation
web.Response toWebResponse(Response response) {
final headers = web.Headers();
response.headers.forEach((key, value) {
if (key.toLowerCase() == 'set-cookie') {
for (final cookie in value.split('\n')) {
if (cookie.isNotEmpty) headers.append(key, cookie);
}
} else {
headers.append(key, value);
}
});
final init = web.ResponseInit(status: response.statusCode, headers: headers);
final hasBody =
response.body.contentLength != 0 &&
!_nullBodyStatuses.contains(response.statusCode);
if (!hasBody) {
// Consume and discard the Dart body so stream producers complete.
response.read().listen(null, cancelOnError: true).cancel();
return web.Response(null, init);
}
return web.Response(_toReadableStream(response.read()), init);
}