Simple example for using Turbos Streams in Go with the Gorilla WebSocket toolkit.
Run the sample using the following command:
$ go run *.go
To use the chat example, open http://localhost:8080/ in your browser.
The frontend connects to the Turbo Stream using plain JavaScript like:
<script src="https://cdn.jsdelivr.net/npm/@hotwired/[email protected]/dist/turbo.es2017-umd.min.js" ></script>
<script>
Turbo.connectStreamSource(new WebSocket("ws://" + document.location.host + "/ws"));
</script>
After that the frontend is connected to the Turbo Stream and get's all messages. Every chat message is appended to the dom element with id board
.
This should work with html markup too but I have not gotten it working yet.
The server receives the new chat message via web socket. Then it wraps the message as Turbo Stream action with action append
and broadcasts it to all subscribers. That way all subscribed users see the new message on the board.
The raw text message sent over the web socket is:
{
"identifier":
"{\"channel\":\"Turbo::StreamsChannel\", \"signed_stream_name\":\"**mysignature**\"}",
"message":
"<turbo-stream action='append' target='board'>
<template>
<p>My new Message</p>
</template>
</turbo-stream>"
}
Based on Gorilla WebSocket Chat Example