From 3f42f2ed014200fdfd4fe1c1c05c9dc8c6809054 Mon Sep 17 00:00:00 2001 From: "Caesar M. Tsai" Date: Tue, 31 Dec 2024 15:36:49 +0800 Subject: [PATCH] feat: Encode function can optimize byte array handling (#42) 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, }) --- sse-encoder.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sse-encoder.go b/sse-encoder.go index 3761b0d..0d26c82 100644 --- a/sse-encoder.go +++ b/sse-encoder.go @@ -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)