WebSocket

This service add support of websockets. It manage the connections and provide you easy way to read and write messages

Register the service into your main.go file:

registry.ServiceProviderSocketRegistry(registerHandler, unregisterHandler func(s *socket.Socket))
1

Access the service:

service.DI().SocketRegistry()
1

To be able to handle new connections you should create your own route and create a handler for it. Your handler should looks like that:

type WebsocketController struct {
}

func (controller *WebsocketController) InitConnection(c *gin.Context) {
	ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		panic(err)
	}

	socketRegistryService, has := service.DI().SocketRegistry()
	if !has {
		panic("Socket Registry is not registered")
	}

	errorLoggerService := service.DI().ErrorLogger()

	connection := &socket.Connection{Send: make(chan []byte, 256), Ws: ws}
	socketHolder := &socket.Socket{
		ErrorLogger: errorLoggerService,
		Connection:  connection,
		ID:          "unique connection hash based on userID, deviceID and timestamp",
		Namespace:   model.DefaultNamespace,
	}

	socketRegistryService.Register <- socketHolder

	go socketHolder.WritePump()
	go socketHolder.ReadPump(socketRegistryService, func(rawData []byte) {
		s, _ := socketRegistryService.Sockets.Load(socketHolder.ID)
		
        dto := &DTOMessage{}
        err = json.Unmarshal(rawData, dto)
        if err != nil {
            errorLoggerService.LogError(err)
            retrun
        }
        //handle business logic here
        s.(*socket.Socket).Emit(dto)
	})
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

This handler initializes the new coming connections and have 2 go routines - one for writing messages and the second one for reading messages If you want to send message you should use socketRegistryService.Emit

If you want to read coming messages you should do it in the function we are passing as second parameter of ReadPump method

If you want to select certain connection you can do it by the ID and this method

s, err := socketRegistryService.Sockets.Load(ID)
1

Also websocket service provide you hooks for registering new connections and for unregistering already existing connections. You can define those handlers when you register the service based on namespace of socket.