Created
March 24, 2024 02:07
-
-
Save dj-nitehawk/8d340c79757d73f2cdb534edf7276cf5 to your computer and use it in GitHub Desktop.
Streaming JSON response with `IAsyncEnumerable`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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