stream function
Future<Response>
stream(
- Context c,
- Future<
void> callback(- DartoStreamWriter writer
- Future<
void> onError(- Object error,
- DartoStreamWriter writer
Streams raw binary data to the client.
Sets Transfer-Encoding: chunked automatically. The callback receives a
DartoStreamWriter to send chunks. Errors in callback are forwarded to
onError; without it they are silently swallowed (the response is always
closed cleanly).
app.get('/bytes', (c) => stream(c, (s) async {
await s.write([72, 101, 108, 108, 111]);
}));
Implementation
Future<Response> stream(
Context c,
Future<void> Function(DartoStreamWriter writer) callback, {
Future<void> Function(Object error, DartoStreamWriter writer)? onError,
}) async {
final httpRes = c.res.raw;
httpRes.statusCode = 200;
httpRes.headers.set(HttpHeaders.transferEncodingHeader, 'chunked');
final writer = DartoStreamWriter._(httpRes);
unawaited(httpRes.done.then((_) {}, onError: (_) {
writer._aborted = true;
writer._onAbortCallback?.call();
}));
try {
await callback(writer);
} catch (e) {
if (onError != null) await onError(e, writer);
} finally {
try {
await httpRes.close();
} catch (_) {}
}
return const Response.sent();
}