Server Sent Events
Use send.SseUpgrade()
to upgrade the connection to server sent events.
route.Route{Pattern: "GET /sse", Handler: welcome.View}
package welcome
import ( "main/lib/core/client" "main/lib/core/receive" "main/lib/core/send" "time")
func View(c *client.Client) { a := receive.IsAlive(c) // Tracks request status. ev := send.SseUpgrade(c) // Sends sse upgrade. for *a { // Loops until cancellation. ev("channel-1") // Switches to "channel-1". send.Message(c, "Hello 1") // Sends message. ev("channel-2") // Switches to "channel-2". send.Message(c, "Hello 2") // Sends message. time.Sleep(time.Second) // Sleeps for 1 second. }}
Then consume the stream on the client.
<script lang="ts"> import {source} from "$lib/scripts/core/source.ts"; const con = source("/sse") // Connects to the handler. const ch1 = c.select("channel-1") // Listens to "channel-1". const ch2 = c.select("channel-2") // Listens to "channel-2".</script>
<h1>Channel 1</h1><span>{$ch1}</span> <!-- Renders most recent value of channel-1. -->
<h1>Channel 2</h1><span>{$ch2}</span> <!-- Renders most recent value of channel-2. -->