Server Sent Events (SSE)

htmgo supports server-sent events (SSE) out of the box.

This allows you to push data from the server to the client in real-time.

Example of this can be found in the examples/chat project.

How it works

1. The client sends a request to the server to establish a connection.

2. The server holds the connection open and sends data (in our case, most likely elements) to the client whenever there is new data to send.

3. The htmgo SSE extension uses hx-swap-oob to swap out the elements that the server sends.

Note: SSE is unidirectional (the server can only send data to the client). For the client to send data to the server, normal xhr behavior should be used (form submission, triggers, etc).

Usage:

Add the SSE connection attribute and the path to the handler that will handle the connection.

Copy
1h.Attribute("sse-connect", fmt.Sprintf("/chat/%s", roomId))

The following Event Handlers can be used to react to SSE connections.

Copy
1h.HxOnSseOpen
2h.HxBeforeSseMessage
3h.HxAfterSseMessage
4h.HxOnSseError
5h.HxOnSseClose
6h.HxOnSseConnecting

Example: Adding an event listener handle SSE errors.

Copy
 1h.HxOnSseError(
 2    js.EvalJs(fmt.Sprintf("
 3			const reason = e.detail.event.data
 4			if(['invalid room', 'no session', 'invalid user'].includes(reason)) {
 5				window.location.href = '/?roomId=%s';
 6			} else if(e.detail.event.code === 1011) {
 7				window.location.reload()
 8			} else if (e.detail.event.code === 1008 || e.detail.event.code === 1006) {
 9				window.location.href = '/?roomId=%s';
10			} else {
11				console.error('Connection closed:', e.detail.event)
12			}
13", roomId, roomId)),
14),

Example: Clearing the input field after sending a message.

Copy
1func MessageInput() *h.Element {
2	return h.Input("text",
3		h.Id("message-input"),
4		h.Required(),
5		h.HxAfterSseMessage(
6			js.SetValue(""),
7		),
8	)
9}