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

Add options to New, WithContext option for cancellation #7

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
26 changes: 25 additions & 1 deletion sse.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ package sse

import (
"bytes"
"context"
"encoding/json"
"net/http"
"strconv"
Expand All @@ -27,22 +28,36 @@ type Streamer struct {
connecting chan client
disconnecting chan client
bufSize uint
ctx context.Context
}

// New returns a new initialized SSE Streamer
func New() *Streamer {
func New(options ...func(*Streamer)) *Streamer {
s := &Streamer{
event: make(chan []byte, 1),
clients: make(map[client]bool),
connecting: make(chan client),
disconnecting: make(chan client),
bufSize: 2,
ctx: context.Background(),
}

for _, apply := range options {
apply(s)
}

s.run()
return s
}

// WithContext will use the provided context for the streamer. The streamer and
// any active connections will immediately close and return upon context.Done().
func WithContext(ctx context.Context) func(s *Streamer) {
return func(s *Streamer) {
s.ctx = ctx
}
}

// run starts a goroutine to handle client connects and broadcast events.
func (s *Streamer) run() {
go func() {
Expand All @@ -64,6 +79,12 @@ func (s *Streamer) run() {
//}
cl <- event
}

case <-s.ctx.Done():
close(s.event)
close(s.connecting)
close(s.disconnecting)
return
}
}
}()
Expand Down Expand Up @@ -258,6 +279,9 @@ func (s *Streamer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Write events
w.Write(event) // TODO: error handling
fl.Flush()

case <-s.ctx.Done():
return
}
}
}
14 changes: 14 additions & 0 deletions sse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,3 +283,17 @@ func TestJSONErr(t *testing.T) {
t.Fatal("wrong body, got:\n", w.written, "\nexpected:\n", expected)
}
}

func TestWithContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())

streamer := New(WithContext(ctx))
w := NewMockResponseWriteFlusher()

go func() {
time.Sleep(500 * time.Millisecond)
cancel()
}()

streamer.ServeHTTP(w, NewMockRequestWithTimeout(5000*time.Millisecond))
}