Skip to content

Commit

Permalink
feat: Encode function can optimize byte array handling (#42)
Browse files Browse the repository at this point in the history
In scenarios where byte array JSON messages are forwarded (e.g., from MQ), the previous approach required unmarshalling into an object before encoding for SSE.

The updated logic allows []byte to be passed directly, simplifying message forwarding and reducing unnecessary conversions.

	// before
	byteData := messageFromMQ()
	data := make(map[string]any)
	json.Unmarshal(byteData, &data)
	sse.Encode(new(bytes.Buffer), sse.Event{
		Data: data,
	})

	// after
	byteData := messageFromMQ()
	sse.Encode(new(bytes.Buffer), sse.Event{
		Data: byteData,
	})
  • Loading branch information
KScaesar authored Dec 31, 2024
1 parent e597170 commit 3f42f2e
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions sse-encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ func writeRetry(w stringWriter, retry uint) {

func writeData(w stringWriter, data interface{}) error {
w.WriteString("data:")

bData, ok := data.([]byte)
if ok {
dataReplacer.WriteString(w, string(bData))
w.WriteString("\n\n")
return nil
}

switch kindOfData(data) {
case reflect.Struct, reflect.Slice, reflect.Map:
err := json.NewEncoder(w).Encode(data)
Expand Down

0 comments on commit 3f42f2e

Please sign in to comment.