Skip to content

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

Notifications You must be signed in to change notification settings

remast/go_websocket_turbo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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>

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 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>"
}

Credits

Based on Gorilla WebSocket Chat Example

About

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

Resources

Stars

Watchers

Forks