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

onSubscribe send a message to the subscriber #177

Open
Cyliann opened this issue Feb 5, 2024 · 1 comment
Open

onSubscribe send a message to the subscriber #177

Cyliann opened this issue Feb 5, 2024 · 1 comment

Comments

@Cyliann
Copy link

Cyliann commented Feb 5, 2024

Is it possible to send a message to the subscriber as soon as it subscribes? I need to send an ID to every new client connected.
Sadly, this doesn't work:

func main() {
        server := sse.New()
	mux := http.NewServeMux()
	mux.HandleFunc("/events", eventHandler)

	http.ListenAndServe(":8080", mux)
}

func eventHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Message"))
	w.(http.Flusher).Flush()

	server.ServeHTTP(w, r)
}

I though that onSubsrcibe() can to that, but it doesn't allow passing http.ResponseWriter in any way and I can't see how it can be accomplished otherwise.
I've been banging my head over the wall for the past 2 days and I can't get it to work.
Could you provide any help?

@Prasannakumar414
Copy link

Hello @Cyliann you can add the headers to keep connection alive and connection type to event stream.
For SSE connection we must have following things

  • Connection as keep-alive
  • Connection Type to be text/event-stream
func main() {
        server := sse.New()
	mux := http.NewServeMux()
	mux.HandleFunc("/events", eventHandler)

	http.ListenAndServe(":8080", mux)
}

func eventHandler(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")
	w.Write([]byte("Message"))
	w.(http.Flusher).Flush()

	server.ServeHTTP(w, r)
}

I have implemented something like this and it is working for me

mux.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) {
		go func() {
			<-r.Context().Done()
			done <- true
			println("The client is disconnected here")
		}()
		w.Header().Set("Content-Type", "text/event-stream")
		w.Header().Set("Cache-Control", "no-cache")
		w.Header().Set("Connection", "keep-alive")
		rc := http.NewResponseController(w)
		_, err := fmt.Fprintf(w, "data:congo on entering to sse\n\n")
		if err != nil {
			return
		}
		err = rc.Flush()
		if err != nil {
			return
		}

		server.ServeHTTP(w, r)
	})

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

No branches or pull requests

2 participants