@@ -174,6 +174,91 @@ ws.On(handler.WebsocketMessage, func(ctx *handler.WebsocketContext, next handler
174
174
})
175
175
```
176
176
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
+
177
262
Do a quick ` go mod tidy ` to make sure all new dependencies are resolved.
178
263
179
264
## Ok, let's run this thing!
0 commit comments