r3labs / sse

Server Sent Events server and client for Golang

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question: connect state

loeffel-io opened this issue · comments

Hey,

thank you for the great library - just want to ask how i can get informations about the connection progress - how i can retrieve errors when there is e.g. a non 200 status code? Is there something like a connection state?

Thank you!

Hey! Glad you like the library!

So any of the Subscribe methods should return an error when the connection is initially set up, which should catch any non-200 HTTP status codes. Once the subscription is setup, it's not possible to get the exact error.

You can get connection status through the OnDisconnect callbacks like so:

c, err := sse.NewClient("http://my-sse-endpoint.net")

c.OnDisconnect(func(c *sse.Client) {
    // log the disconnect
})

If you are interested in making use of those errors, I'm happy to extend the OnDisconnect callback to expose those errors?

Thanks for your answer!

sse.NewClient don't return a error btw

I am using SubscribeRaw which is not returning an error for 401 - maybe i miss something?

var client = sse.NewClient("https://localhost:3003/api/auth/company/1/group/1/message/event")

if err := client.SubscribeRaw(func(event *sse.Event) {
    // foo
}); err != nil {
    logger.Fatal(err)
}

Edit:

Tested with a lot of 401 errors

[GIN] 2021/02/24 - 14:38:37 | 401 |      73.436µs |      172.20.0.1 | GET      "/api/auth/company/1/group/1/message/event"
[GIN] 2021/02/24 - 14:38:37 | 401 |      71.115µs |      172.20.0.1 | GET      "/api/auth/company/1/group/1/message/event"
[GIN] 2021/02/24 - 14:38:40 | 401 |      55.977µs |      172.20.0.1 | GET      "/api/auth/company/1/group/1/message/event"
[GIN] 2021/02/24 - 14:38:40 | 401 |     104.201µs |      172.20.0.1 | GET      "/api/auth/company/1/group/1/message/event"
[GIN] 2021/02/24 - 14:38:42 | 401 |      41.281µs |      172.20.0.1 | GET      "/api/auth/company/1/group/1/message/event"

Got it by using the ReconnectNotify handler

Returning the status code here could be pretty helpful: https://github.com/r3labs/sse/blob/master/client.go#L77

Cool, thank you for testing that out. Subscribe* should eventually return the error, however the exponential backoff will loop forever by default. You can avoid this by doing something like:

c := NewClient(url)

c.ReconnectStrategy = backoff.WithMaxTries(
    backoff.NewExponentialBackOff(), 
    3,
)

The above PR should include the http status in the error

Thanks @purehyperbole for the info!

Just built up this tool for testing our scalable redis sse events and it works great 🎉

https://github.com/makeless/makeless-go-event-client