Go - Websocket.Close()

Closes a connection to a websocket

import (
  "context"
  "fmt"

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

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

  ws.Close(context.TODO(), "D28BA458-BFF4-404A")

  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 be closed.

Examples

Close a connection to the websocket on message

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
	}

	// Broadcast message to all the registered websocket connections
	ws.On(handler.WebsocketMessage, func(ctx *handler.WebsocketContext, next handler.WebsocketHandler) (*handler.WebsocketContext, error) {
		if ctx.Request.Message() == "close" {
			err := ws.Close(context.Background(), ctx.Request.ConnectionID())
			return ctx, err
		}

		return next(ctx)
	})

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