Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ResponseValidator & ReconnectNotify #77

Merged
merged 3 commits into from
Jun 29, 2020
Merged

ResponseValidator & ReconnectNotify #77

merged 3 commits into from
Jun 29, 2020

Conversation

hermanbanken
Copy link
Contributor

@hermanbanken hermanbanken commented Jun 29, 2020

Given the code

// in a goroutine:
for {
	err := client.SubscribeRawWithContext(ctx, func(msg *sse.Event) {
		logger.Printf("SSE Message ID=%q Retry=%q Event=%q len(Data)=%d\n", string(msg.ID), string(msg.Retry), string(msg.Event), len(msg.Data))
	})
	if err != nil {
		logger.Println("SubscribeRawWithContext stopped:", err)
	} else {
		logger.Println("SubscribeRawWithContext done; retrying")
		time.Sleep(1 * time.Second)
	}
}

the SubscribeRawWithContext method would be called every 1 second if the HTTP request returns a StatusCode other than 200 without a stream result. This happens because the EventStreamReader.startReadLoop will convert io.EOF into a non-error. This gives the users of the SSE lib no context as to why the SubscribeRawWithContext is called every single second (and without the Sleep even continuously).

I made 2 adjustments:

  • use RetryNotify of the backoff library, to enable possibly getting feedback when a retry happens
  • add a ResponseValidator callback that can return an error based on an invalid HTTP response (like not text/event-stream or not 200 OK)

Users can do:

client.ResponseValidator = func(c *sse.Client, resp *http.Response) error {
	if resp.Header.Get("Content-Type") != "text/event-stream" || resp.StatusCode != 200 {
		return fmt.Errorf("Invalid StatusCode %d: %s", resp.StatusCode, resp.Status)
	}
	return nil
}

and

client.ReconnectNotify = func(err error, backoff time.Duration) {
	logger.Println("Reconnect", err, backoff)
}

Without a ResponseValidator this is fully backwards compatible.

@purehyperbole
Copy link
Member

Awesome, thanks for submitting these changes. I'll merge now and cut a release!

@purehyperbole purehyperbole merged commit c9bb0c8 into r3labs:master Jun 29, 2020
@hermanbanken
Copy link
Contributor Author

Wow that was fast. Thanks! 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants