-
Notifications
You must be signed in to change notification settings - Fork 1.8k
added built in SSE support in GoFr #3044
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
Open
IronwallxR5
wants to merge
15
commits into
gofr-dev:development
Choose a base branch
from
IronwallxR5:build-in-sse-suport
base: development
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 6 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
1475fe2
added buid in SSE support in GoFr
IronwallxR5 2bab9f9
fix: resolve golangci-lint violations in SSE implementation
IronwallxR5 8b26c84
fixed code quality
IronwallxR5 b0dfd86
switch SSE to sequential Responder callback
IronwallxR5 1762962
fix golangci-lint errors in sse tests
IronwallxR5 860acff
Merge branch 'development' into build-in-sse-suport
Umang01-hash d964993
address review feedback on sse implementation
IronwallxR5 9089301
fixed typo in responder.go
IronwallxR5 76b46bf
Merge branch 'development' into build-in-sse-suport
IronwallxR5 597ad89
Merge branch 'development' into build-in-sse-suport
IronwallxR5 7ffa346
address maintainer re-review feedback(typed callback, missing tests, …
IronwallxR5 845abb0
Merge branch 'development' into build-in-sse-suport
IronwallxR5 3d83e79
resolve err113 lint failure
IronwallxR5 da0cc7a
Merge branch 'development' into build-in-sse-suport
IronwallxR5 5e3e312
Merge branch 'development' into build-in-sse-suport
IronwallxR5 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| APP_NAME=using-sse | ||
| HTTP_PORT=9000 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "time" | ||
|
|
||
| "gofr.dev/pkg/gofr" | ||
| ) | ||
|
|
||
| func main() { | ||
| app := gofr.New() | ||
|
|
||
| // Stream the current time every second. | ||
| app.GET("/events", func(c *gofr.Context) (any, error) { | ||
| return gofr.SSEResponse(func(stream *gofr.SSEStream) error { | ||
| ticker := time.NewTicker(time.Second) | ||
| defer ticker.Stop() | ||
|
|
||
| i := 0 | ||
|
|
||
| for { | ||
| select { | ||
| case <-c.Context.Done(): | ||
| return nil | ||
| case t := <-ticker.C: | ||
| if err := stream.Send(gofr.SSEEvent{ | ||
| ID: fmt.Sprintf("%d", i), | ||
| Name: "time", | ||
| Data: map[string]string{"time": t.Format(time.RFC3339)}, | ||
| }); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| i++ | ||
| } | ||
| } | ||
| }), nil | ||
| }) | ||
|
|
||
| // A countdown that sends 11 events and closes. | ||
| app.GET("/countdown", func(c *gofr.Context) (any, error) { | ||
| return gofr.SSEResponse(func(stream *gofr.SSEStream) error { | ||
| for i := 10; i >= 0; i-- { | ||
| select { | ||
| case <-c.Context.Done(): | ||
| return nil | ||
| default: | ||
| if err := stream.SendEvent("countdown", map[string]int{"remaining": i}); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| time.Sleep(500 * time.Millisecond) | ||
IronwallxR5 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
|
|
||
| return stream.SendEvent("done", "Countdown complete!") | ||
| }), nil | ||
| }) | ||
|
|
||
| app.Run() | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| package response | ||
|
|
||
| import ( | ||
| "net/http" | ||
| ) | ||
|
|
||
| // SSE represents a Server-Sent Events response. | ||
| // Return this from a handler to stream events to the client. | ||
| type SSE struct { | ||
| // Stream uses the provided ResponseWriter to send Server-Sent Events. | ||
| Stream func(w http.ResponseWriter) error | ||
IronwallxR5 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| package gofr | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "fmt" | ||
| "net/http" | ||
| "strings" | ||
|
|
||
| "gofr.dev/pkg/gofr/http/response" | ||
| ) | ||
|
|
||
| // SSEEvent represents a single Server-Sent Event. | ||
| type SSEEvent struct { | ||
| Name string // Event type (event: field) | ||
| Data any // Event data (data: field) - strings pass through, others are JSON-encoded | ||
| ID string // Event ID (id: field) | ||
| Retry int // Reconnection time in milliseconds (retry: field) | ||
| } | ||
|
|
||
| // SSEStream writes Server-Sent Events directly to the HTTP response. | ||
| // It wraps an http.ResponseWriter and flushes after each event. | ||
| type SSEStream struct { | ||
IronwallxR5 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| w http.ResponseWriter | ||
| rc *http.ResponseController | ||
| } | ||
|
|
||
| // SSEFunc is the callback signature for SSE handlers. | ||
| // The function receives an SSEStream to write events. | ||
| type SSEFunc func(stream *SSEStream) error | ||
|
|
||
| // SSEResponse creates an SSE response that can be returned from a handler. | ||
| // The callback function is called by the Responder to produce SSE events. | ||
| // | ||
| // Example: | ||
| // | ||
| // app.GET("/events", func(c *gofr.Context) (any, error) { | ||
| // return gofr.SSEResponse(func(stream *gofr.SSEStream) error { | ||
| // for i := 0; i < 10; i++ { | ||
| // if err := stream.SendEvent("counter", i); err != nil { | ||
| // return err | ||
| // } | ||
| // time.Sleep(time.Second) | ||
| // } | ||
| // return nil | ||
| // }), nil | ||
| // }) | ||
| func SSEResponse(callback SSEFunc) response.SSE { | ||
| return response.SSE{ | ||
| Stream: func(w http.ResponseWriter) error { | ||
| stream := &SSEStream{ | ||
IronwallxR5 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| w: w, | ||
| rc: http.NewResponseController(w), | ||
| } | ||
| return callback(stream) | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| // Send writes a formatted SSE event to the stream and flushes. | ||
| func (s *SSEStream) Send(event any) error { | ||
IronwallxR5 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| sseEvent, ok := event.(SSEEvent) | ||
| if !ok { | ||
| // If not an SSEEvent, treat as data-only event | ||
| return s.SendData(event) | ||
| } | ||
|
|
||
| raw, err := formatEvent(sseEvent) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| if _, err := fmt.Fprint(s.w, raw); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| return s.rc.Flush() | ||
| } | ||
|
|
||
| // SendData is shorthand for Send(SSEEvent{Data: data}). | ||
| func (s *SSEStream) SendData(data any) error { | ||
| return s.Send(SSEEvent{Data: data}) | ||
| } | ||
|
|
||
| // SendEvent is shorthand for Send(SSEEvent{Name: name, Data: data}). | ||
| func (s *SSEStream) SendEvent(name string, data any) error { | ||
| return s.Send(SSEEvent{Name: name, Data: data}) | ||
| } | ||
|
|
||
| // SendComment writes an SSE comment (: prefix) to the stream. | ||
| // Comments are often used as keep-alive heartbeats. | ||
| func (s *SSEStream) SendComment(text string) error { | ||
| var sb strings.Builder | ||
|
|
||
| for _, line := range strings.Split(text, "\n") { | ||
| fmt.Fprintf(&sb, ": %s\n", line) | ||
| } | ||
|
|
||
| sb.WriteString("\n") | ||
|
|
||
| if _, err := fmt.Fprint(s.w, sb.String()); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| return s.rc.Flush() | ||
| } | ||
|
|
||
| // formatEvent builds the wire-format string for one SSE event. | ||
| func formatEvent(event SSEEvent) (string, error) { | ||
| var sb strings.Builder | ||
|
|
||
| if event.ID != "" { | ||
| fmt.Fprintf(&sb, "id: %s\n", event.ID) | ||
| } | ||
|
|
||
| if event.Name != "" { | ||
| fmt.Fprintf(&sb, "event: %s\n", event.Name) | ||
| } | ||
|
|
||
| if event.Retry > 0 { | ||
| fmt.Fprintf(&sb, "retry: %d\n", event.Retry) | ||
| } | ||
|
|
||
| dataStr, err := formatSSEData(event.Data) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
|
|
||
| for _, line := range strings.Split(dataStr, "\n") { | ||
| fmt.Fprintf(&sb, "data: %s\n", line) | ||
| } | ||
|
|
||
| sb.WriteString("\n") | ||
|
|
||
| return sb.String(), nil | ||
| } | ||
|
|
||
| // formatSSEData converts data to a string for SSE. | ||
| // Strings and []byte pass through; everything else is JSON-encoded. | ||
| func formatSSEData(data any) (string, error) { | ||
| switch v := data.(type) { | ||
| case string: | ||
| return v, nil | ||
| case []byte: | ||
| return string(v), nil | ||
| case nil: | ||
| return "", nil | ||
| default: | ||
| b, err := json.Marshal(v) | ||
| if err != nil { | ||
| return "", fmt.Errorf("failed to marshal SSE data: %w", err) | ||
| } | ||
|
|
||
| return string(b), nil | ||
| } | ||
| } | ||
IronwallxR5 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.