Server-Sent Events

A demo countdown using Server-Sent Events, with htmx and typed-htmx-go.

When you click the button below, that fetches a new element that uses the sse extension to start stream a countdown.

return Button(
	hx.Get("/examples/gomponents/sse/countdown/"),
	hx.Target(htmx.TargetThis),
	hx.Swap(swap.OuterHTML),
	g.Text("Start Countdown"),
)

The new elements uses the sse.Connect attribute to connect to a server-sent event streaming countdown.

return Div(
	hx.Ext(sse.Extension),
	sse.Connect(hx, "/examples/gomponents/sse/countdown/feed/"),
	sse.Swap(hx, shared.ResetEvent),
	hx.Swap(swap.OuterHTML),
	Div(
		sse.Swap(hx, shared.CountdownEvent),
		hx.Swap(swap.InnerHTML),
	),
)

Each second, the server sends a countdown message that updates the innerHTML of the div.

func Message(msg string) g.Node {
	return P(g.Text(msg))
}

func Blastoff() g.Node {
	return P(g.Text("Blastoff!"))
}

After the countdown is complete, the server will send a ResetEvent, that closes removes the sse connection by replacing the sse.Connect element with the initial button using<code>hx.Swap(swap.OuterHTML)</code>.

Demo