Go - Websocket.Send()

Send a message from the websocket to a connection.

import (
  "context"
  "fmt"

  "github.com/nitrictech/go-sdk/nitric"
)

func main() {
  ws, err := nitric.NewWebsocket("public")
  if err != nil {
    return
  }

  ws.Send(context.TODO(), "D28BA458-BFF4-404A", []byte("Hello World"))

  if err := nitric.Run(); err != nil {
    fmt.Println(err)
  }
}

Parameters

  • Name
    ctx
    Required
    Required
    Type
    context
    Description

    The context of the call, used for tracing.

  • Name
    connectionId
    Required
    Required
    Type
    string
    Description

    The ID of the connection which should receive the message.

  • Name
    message
    Required
    Required
    Type
    []byte
    Description

    The message that should be sent to the connection.

Examples

Broadcasting a message to all connections.

import (
  "fmt"

  "github.com/nitrictech/go-sdk/faas"
  "github.com/nitrictech/go-sdk/nitric"
)

func main() {
  ws, err := nitric.NewWebsocket("public")
  if err != nil {
    return
  }

  connections, err := nitric.NewCollection("connections").With(nitric.CollectionEverything...)
  if err != nil {
    return
  }

  // Register a new connection on connect
  ws.On(faas.WebsocketConnect, func(ctx *faas.WebsocketContext, next faas.WebsocketHandler) (*faas.WebsocketContext, error) {
    err := connections.Doc(ctx.Request.ConnectionID()).Set(ctx.Request.Context(), map[string]interface{}{
      "connectionId": ctx.Request.ConnectionID(),
    })
    if err != nil {
      return ctx, err
    }

    return next(ctx)
  })

  // Remove a registered connection on disconnect
  ws.On(faas.WebsocketDisconnect, func(ctx *faas.WebsocketContext, next faas.WebsocketHandler) (*faas.WebsocketContext, error) {
    err := connections.Doc(ctx.Request.ConnectionID()).Delete(ctx.Request.Context())
    if err != nil {
      return ctx, err
    }

    return next(ctx)
  })

  // Broadcast message to all the registered websocket connections
  ws.On(faas.WebsocketMessage, func(ctx *faas.WebsocketContext, next faas.WebsocketHandler) (*faas.WebsocketContext, error) {
    connectionStream, err := connections.Query().Stream(ctx.Request.Context())
    if err != nil {
      return ctx, err
    }

    for {
      res, err := connectionStream.Next()
      if err != nil {
        break // reached the end of the documents
      }

      connectionId, ok := res.Content()["connectionId"].(string)
      if !ok {
        continue
      }

      err = ws.Send(ctx.Request.Context(), connectionId, ctx.Request.Data())
      if err != nil {
        return ctx, err
      }
    }

    return next(ctx)
  })

  if err := nitric.Run(); err != nil {
    fmt.Println(err)
  }
}