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 (
	"context"
	"fmt"

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

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

	connections, err := nitric.NewKv("connections").Allow(nitric.KvStoreGet, nitric.KvStoreSet, nitric.KvStoreDelete)
	if err != nil {
		return
	}

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

		return next(ctx)
	})

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

		return next(ctx)
	})

	// Broadcast message to all the registered websocket connections
	ws.On(handler.WebsocketMessage, func(ctx *handler.WebsocketContext, next handler.WebsocketHandler) (*handler.WebsocketContext, error) {
		connectionStream, err := connections.Keys(context.TODO())
		if err != nil {
			return ctx, err
		}

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

			err = ws.Send(context.TODO(), connectionId, []byte(ctx.Request.Message()))
			if err != nil {
				return ctx, err
			}
		}

		return next(ctx)
	})

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