DEV Community

Cover image for Turbo Streams powered by Go WebSockets
Jan Stamer
Jan Stamer

Posted on

Turbo Streams powered by Go WebSockets

Turbo is a new way to build greate web frontends fully powered by html markup and without any JavaScript. That Turbo is what powers Basecamps new mail service HeyHey.

At the heart of Turbo are Streams which provides realtime updates over HTTP or WebSocket.

With Turbo Streams you just sent dom updates over the wire as plain html. Like so:

<turbo-stream action="append" target="dom_id">
  <template>
    Content to append to container designated with the dom_id.
  </template>
</turbo-stream>
Enter fullscreen mode Exit fullscreen mode

Then the html sent over in the template element is appended to the dom element with id dom_id. Just so simple. Of course you can also replace or remove html from the dom the same way by using the actions repace and remove.

For all you Gophers out there keen on using it, I've got you covered! Here's a simple example for using Turbos Streams in Go
with the Gorilla WebSocket toolkit.

GitHub logo remast / go_websocket_turbo

Simple example for using Turbos Streams in Go with the Gorilla WebSocket toolkit.

Go Example for TurboStreams over WebSockets

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.

Frontend

The frontend connects to the Turbo Stream using plain JavaScript like:

<script src="https://cdn.jsdelivr.net/npm/@hotwired/turbo@8.0.4/dist/turbo.es2017-umd.min.js" ></script>
<script>
Turbo.connectStreamSource(new WebSocket("ws://" + document.location.host + "/ws"));
</script>
Enter fullscreen mode Exit fullscreen mode

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.

Server

The server receives the new chat message via web socket. Then it wraps the message as Turbo Stream…




Top comments (0)