Skip to content
This repository was archived by the owner on May 20, 2025. It is now read-only.

Commit 715e936

Browse files
committed
Add full code snippet as suggested.
1 parent 848224d commit 715e936

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

src/pages/guides/go/realtime-messaging.mdx

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,91 @@ ws.On(handler.WebsocketMessage, func(ctx *handler.WebsocketContext, next handler
174174
})
175175
```
176176

177+
### Bringing it all together
178+
179+
<details>
180+
<summary>Your code should look like this:</summary>
181+
182+
```go
183+
package main
184+
185+
import (
186+
"context"
187+
"fmt"
188+
189+
"github.com/nitrictech/go-sdk/handler"
190+
"github.com/nitrictech/go-sdk/nitric"
191+
)
192+
193+
func main() {
194+
ws, err := nitric.NewWebsocket("public")
195+
if err != nil {
196+
fmt.Println("Error creating WebSocket:", err)
197+
return
198+
}
199+
200+
connections, err := nitric.NewKv("connections").Allow(nitric.KvStoreGet, nitric.KvStoreSet, nitric.KvStoreDelete)
201+
if err != nil {
202+
fmt.Println("Error creating KV store:", err)
203+
return
204+
}
205+
206+
ws.On(handler.WebsocketConnect, func(ctx *handler.WebsocketContext, next handler.WebsocketHandler) (*handler.WebsocketContext, error) {
207+
err := connections.Set(context.TODO(), ctx.Request.ConnectionID(), map[string]interface{}{
208+
"connectionId": ctx.Request.ConnectionID(),
209+
})
210+
if err != nil {
211+
return ctx, err
212+
}
213+
214+
return next(ctx)
215+
})
216+
217+
ws.On(handler.WebsocketDisconnect, func(ctx *handler.WebsocketContext, next handler.WebsocketHandler) (*handler.WebsocketContext, error) {
218+
err := connections.Delete(context.TODO(), ctx.Request.ConnectionID())
219+
if err != nil {
220+
return ctx, err
221+
}
222+
223+
return next(ctx)
224+
})
225+
226+
ws.On(handler.WebsocketMessage, func(ctx *handler.WebsocketContext, next handler.WebsocketHandler) (*handler.WebsocketContext, error) {
227+
connectionStream, err := connections.Keys(context.TODO())
228+
if err != nil {
229+
return ctx, err
230+
}
231+
232+
senderId := ctx.Request.ConnectionID()
233+
234+
for {
235+
connectionId, err := connectionStream.Recv()
236+
if err != nil {
237+
break
238+
}
239+
240+
if connectionId == senderId {
241+
continue
242+
}
243+
244+
message := fmt.Sprintf("%s: %s", senderId, ctx.Request.Message())
245+
err = ws.Send(context.TODO(), connectionId, []byte(message))
246+
if err != nil {
247+
return ctx, err
248+
}
249+
}
250+
251+
return next(ctx)
252+
})
253+
254+
if err := nitric.Run(); err != nil {
255+
fmt.Println("Error running Nitric service:", err)
256+
}
257+
}
258+
```
259+
260+
</details>
261+
177262
Do a quick `go mod tidy` to make sure all new dependencies are resolved.
178263

179264
## Ok, let's run this thing!

0 commit comments

Comments
 (0)