danielgtaylor / huma

Huma REST/HTTP API Framework for Golang with OpenAPI 3.1
https://huma.rocks/
MIT License
1.9k stars 139 forks source link

Example for handling long lived SSE connections #286

Closed IcelandicIcecream closed 6 months ago

IcelandicIcecream commented 6 months ago

Hey! Great work on the framework, gonna use it for most of my projects from now on. Just wanted to ask if there is an example for a long lived SSE connection. Like how do I handle user disconnects and etc. Also, how do I handle errors for SSE connections? Im using the example with send.Data as reference

Insei commented 6 months ago

Hi! You can check that you client is alive by send.Data(), this func return error if connection lost or connection has any other error. For example you can send ping event every 10s. Yep, this is not perfect solution, but it can works correctly.

IcelandicIcecream commented 6 months ago

Hi! You can check that you client is alive by send.Data(), this func return error if connection lost or connection has any other error. For example you can send ping event every 10s. Yep, this is not perfect solution, but it can works correctly.

Alright. thanks for the suggestion! Will do this in the meantime. If I remember correctly, maybe we can actually run a separate goroutine to check for ctx.Done(). Will do some testing and let you know!

danielgtaylor commented 6 months ago

@IcelandicIcecream FYI there is a more complete FizzBuzz SSE example here:

https://github.com/danielgtaylor/huma/blob/main/examples/sse/main.go

It includes ending the handler when send.Data(...) fails:

https://github.com/danielgtaylor/huma/blob/main/examples/sse/main.go#L156-L158

danielgtaylor commented 6 months ago

Please let me know if the provided examples don't answer your question, and feel free to re-open if needed!