streamText function
Future<Response>
streamText(
- Context c,
- Future<
void> callback(- DartoTextStreamWriter writer
- Future<
void> onError(- Object error,
- DartoTextStreamWriter writer
Streams plain text to the client chunk by chunk.
Sets Content-Type: text/plain and Transfer-Encoding: chunked
automatically. The callback receives a DartoTextStreamWriter.
app.get('/words', (c) => streamText(c, (s) async {
for (final word in ['Hello', ' ', 'World']) {
await s.write(word);
await s.sleep(Duration(milliseconds: 300));
}
}));
Implementation
Future<Response> streamText(
Context c,
Future<void> Function(DartoTextStreamWriter writer) callback, {
Future<void> Function(Object error, DartoTextStreamWriter writer)? onError,
}) async {
final httpRes = c.res.raw;
httpRes.statusCode = 200;
httpRes.headers.contentType = ContentType.text;
httpRes.headers.set(HttpHeaders.transferEncodingHeader, 'chunked');
final writer = DartoTextStreamWriter._(httpRes);
try {
await callback(writer);
} catch (e) {
if (onError != null) await onError(e, writer);
} finally {
try {
await httpRes.close();
} catch (_) {}
}
return const Response.sent();
}