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

Fix panic on sse-server shutdown #36

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix panic on Shutdown when there is at least one active connection
hotafrika committed Jun 9, 2023
commit de4a9a46b683f6c28a2925dce10667c02077c43c
17 changes: 13 additions & 4 deletions sse.go
Original file line number Diff line number Diff line change
@@ -76,14 +76,24 @@ func (s *Server) ServeHTTP(response http.ResponseWriter, request *http.Request)
channelName = s.options.ChannelNameFunc(request)
}

select {
case <-s.shutdown:
http.Error(response, "SSE server is in termination state.", http.StatusServiceUnavailable)
return
default:
}

lastEventID := request.Header.Get("Last-Event-ID")
c := newClient(lastEventID, channelName)
s.addClient <- c
closeNotify := request.Context().Done()

go func() {
<-closeNotify
s.removeClient <- c
select {
case <-s.shutdown:
case <-closeNotify:
s.removeClient <- c
}
}()

response.WriteHeader(http.StatusOK)
@@ -128,7 +138,7 @@ func (s *Server) Restart() {

// Shutdown performs a graceful server shutdown.
func (s *Server) Shutdown() {
s.shutdown <- true
close(s.shutdown)
}

// ClientCount returns the number of clients connected to this server.
@@ -255,7 +265,6 @@ func (s *Server) dispatch() {
close(s.addClient)
close(s.removeClient)
close(s.closeChannel)
close(s.shutdown)

s.options.Logger.Print("server stopped.")
return