Example #1
0
/**
 * Internal handler for websockets connections
 */
func wsHandler(ws *websocket.Conn) {

	// Increment connections count, set the local one and add to collection map
	connectionsCount++
	connectionId := connectionsCount
	wsConnections[connectionId] = ws

	// Endless loop for WS messages listener
	for {

		// Fetch message (looks blocking thing while not messages)
		var in string
		if err := websocket.Message.Receive(ws, &in); err != nil {
			fmt.Println(err.Error())
			break
		}
		fmt.Printf("Received: %s\n", in)

		// Unwrap/parse bytes into our message type
		inMsg := models.WsMessage{}
		if err := json.Unmarshal([]byte(in), &inMsg); err != nil {
			fmt.Println(err.Error())
			break
		}

		// TODO: Perform Token validation etc.

		// Set source and connection data into message
		// TODO: Possible to init this in model struct?
		inMsg.Source = "mcp.ws"
		inMsg.ConnectionType = "websocket"
		inMsg.ConnectionId = connectionId

		// Call handler
		go HandleRequestMessage(inMsg.BaseMessage)
	}
}