Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Created March 24, 2024 02:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dj-nitehawk/8d340c79757d73f2cdb534edf7276cf5 to your computer and use it in GitHub Desktop.
Save dj-nitehawk/8d340c79757d73f2cdb534edf7276cf5 to your computer and use it in GitHub Desktop.
Streaming JSON response with `IAsyncEnumerable`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Streaming Response Viewer</title>
<script>
async function streamResponse(url) {
const response = await fetch(url);
const reader = response.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
document.getElementById('responseContent').innerText += new TextDecoder().decode(value);
}
}
window.onload = function() {
streamResponse('http://localhost:5001/stream');
};
</script>
</head>
<body>
<pre id="responseContent"></pre>
</body>
</html>
sealed class StreamEndpoint : EndpointWithoutRequest
{
public override void Configure()
{
Get("stream");
AllowAnonymous();
}
public override async Task HandleAsync(CancellationToken ct)
{
//simply provide any IAsyncEnumerable<T> as argument
await SendAsync(GetDataStream(ct));
}
static async IAsyncEnumerable<object> GetDataStream([EnumeratorCancellation] CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
await Task.Delay(1000);
yield return new { guid = Guid.NewGuid() };
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment