2
0
Caesar M. Tsai 3f42f2ed01 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,
	})
2024-12-31 15:36:49 +08:00
2021-08-20 13:37:44 +02:00
2015-05-22 19:23:40 +02:00
2021-08-23 16:06:52 +02:00
2022-04-04 19:19:04 +08:00
2016-01-26 19:01:36 +01:00
2015-05-30 11:23:56 +02:00

Server-Sent Events

Go Reference Build Status codecov Go Report Card

Server-sent events (SSE) is a technology where a browser receives automatic updates from a server via HTTP connection. The Server-Sent Events EventSource API is standardized as part of HTML5[1] by the W3C.

Sample code

import "github.com/gin-contrib/sse"

func httpHandler(w http.ResponseWriter, req *http.Request) {
	// data can be a primitive like a string, an integer or a float
	sse.Encode(w, sse.Event{
		Event: "message",
		Data:  "some data\nmore data",
	})

	// also a complex type, like a map, a struct or a slice
	sse.Encode(w, sse.Event{
		Id:    "124",
		Event: "message",
		Data: map[string]interface{}{
			"user":    "manu",
			"date":    time.Now().Unix(),
			"content": "hi!",
		},
	})
}
event: message
data: some data\\nmore data

id: 124
event: message
data: {"content":"hi!","date":1431540810,"user":"manu"}
 

Content-Type

fmt.Println(sse.ContentType)
text/event-stream

Decoding support

There is a client-side implementation of SSE coming soon.

S
Description
Server-Sent Events implementation in Go. Used by the Gin Framework.
Readme 169 KiB
Languages
Go 100%