WebSockets

Overview

Go-Mojito provides you with an easy way to create websocket endpoints. They are created exactly the same as a regular endpoint, whenever your handler is called, you can be sure it is a websocket connection!

  • Built-in Implementation available
  • Can be replaced
  • Single Implementation only
  • Automatic JSON conversion

Since this is a request argument, there is no multi-implementation as you can only register one factory per type. The automatic JSON conversion works for maps, structs, interfaces and pointers to said types.

Quick Start

  1. Create a new Go-Mojito Handler that has a websocket.Context argument. This example is an echo endpoint.

    func SomeHandler(ctx websocket.Context) {
        for !ctx.Closed() {
            var msg string
            ctx.Receive(&msg)
            ctx.Send(msg)
        }
    }
  2. Go-Mojito will now detect that you expect a websocket connection for this handler and will only call your handler if there is an incoming websocket connection.

  3. Register your handler on a GET route. WebSockets are usually initiated with a GET request. If this differs for your client for some reason, adjust accordingly.

    mojito.GET("/ws", SomeHandler)

FAQ

Go-Mojito offers a helper package to easily create websockets that allow for multiple use-cases at the same time. You can create a websocket that is split up in channels

package main

import (
	"github.com/go-mojito/mojito"
	"github.com/go-mojito/mojito/websocket"
)

func Ping(ctx *websocket.ChannelContext) error { return ctx.Send("Pong") }

func Echo(ctx *websocket.ChannelContext) error {
	var payload interface{}
	ctx.Read(&payload)
	return ctx.Send(payload)
}

func CatchAll(ctx *websocket.ChannelContext) error { return ctx.Send("Channel not found :(") }

func main() {
	mojito.GET("/ws", websocket.New().
		WithChannel("Echo", Echo).
		WithChannel("Ping", Ping).
		WithCatchAll(CatchAll))

	mojito.ListenAndServe(":8123")
}

You can then connect to the websocket can call your channels with a JSON like this.

{"channel": "Echo", "payload": {"can": "be anything"}}