You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
WebSocket wrapper for Fiber with events support and inspired by Socket.io
Note: Requires Go 1.20 and above
Install
go get -u github.com/gofiber/fiber/v2
go get -u github.com/gofiber/contrib/socketio
Signatures
// Initialize new socketio in the callback this will// execute a callback that expects kws *Websocket Object// and optional config websocket.ConfigfuncNew(callbackfunc(kws*Websocket), config...websocket.Config) func(*fiber.Ctx) error
// Add listener callback for an event into the listeners listfuncOn(eventstring, callbackfunc(payload*EventPayload))
// Emit the message to a specific socket uuids list// Ignores all errorsfuncEmitToList(uuids []string, message []byte)
// Emit to a specific socket connectionfuncEmitTo(uuidstring, message []byte) error
// Broadcast to all the active connections// except avoid broadcasting the message to itselffuncBroadcast(message []byte)
// Fire custom event on all connectionsfuncFire(eventstring, data []byte)
Example
package main
import (
"encoding/json""fmt""log""github.com/gofiber/contrib/socketio""github.com/gofiber/contrib/websocket""github.com/gofiber/fiber/v2"
)
// MessageObject Basic chat message objecttypeMessageObjectstruct {
Datastring`json:"data"`Fromstring`json:"from"`Eventstring`json:"event"`Tostring`json:"to"`
}
funcmain() {
// The key for the map is message.toclients:=make(map[string]string)
// Start a new Fiber applicationapp:=fiber.New()
// Setup the middleware to retrieve the data sent in first GET requestapp.Use(func(c*fiber.Ctx) error {
// IsWebSocketUpgrade returns true if the client// requested upgrade to the WebSocket protocol.ifwebsocket.IsWebSocketUpgrade(c) {
c.Locals("allowed", true)
returnc.Next()
}
returnfiber.ErrUpgradeRequired
})
// Multiple event handling supportedsocketio.On(socketio.EventConnect, func(ep*socketio.EventPayload) {
fmt.Printf("Connection event 1 - User: %s", ep.Kws.GetStringAttribute("user_id"))
})
// Custom event handling supportedsocketio.On("CUSTOM_EVENT", func(ep*socketio.EventPayload) {
fmt.Printf("Custom event - User: %s", ep.Kws.GetStringAttribute("user_id"))
// --->// DO YOUR BUSINESS HERE// --->
})
// On message eventsocketio.On(socketio.EventMessage, func(ep*socketio.EventPayload) {
fmt.Printf("Message event - User: %s - Message: %s", ep.Kws.GetStringAttribute("user_id"), string(ep.Data))
message:=MessageObject{}
// Unmarshal the json message// {// "from": "<user-id>",// "to": "<recipient-user-id>",// "event": "CUSTOM_EVENT",// "data": "hello"//}err:=json.Unmarshal(ep.Data, &message)
iferr!=nil {
fmt.Println(err)
return
}
// Fire custom event based on some// business logicifmessage.Event!="" {
ep.Kws.Fire(message.Event, []byte(message.Data))
}
// Emit the message directly to specified usererr=ep.Kws.EmitTo(clients[message.To], ep.Data, socketio.TextMessage)
iferr!=nil {
fmt.Println(err)
}
})
// On disconnect eventsocketio.On(socketio.EventDisconnect, func(ep*socketio.EventPayload) {
// Remove the user from the local clientsdelete(clients, ep.Kws.GetStringAttribute("user_id"))
fmt.Printf("Disconnection event - User: %s", ep.Kws.GetStringAttribute("user_id"))
})
// On close event// This event is called when the server disconnects the user actively with .Close() methodsocketio.On(socketio.EventClose, func(ep*socketio.EventPayload) {
// Remove the user from the local clientsdelete(clients, ep.Kws.GetStringAttribute("user_id"))
fmt.Printf("Close event - User: %s", ep.Kws.GetStringAttribute("user_id"))
})
// On error eventsocketio.On(socketio.EventError, func(ep*socketio.EventPayload) {
fmt.Printf("Error event - User: %s", ep.Kws.GetStringAttribute("user_id"))
})
app.Get("/ws/:id", socketio.New(func(kws*socketio.Websocket) {
// Retrieve the user id from endpointuserId:=kws.Params("id")
// Add the connection to the list of the connected clients// The UUID is generated randomly and is the key that allow// socketio to manage Emit/EmitTo/Broadcastclients[userId] =kws.UUID// Every websocket connection has an optional session key => value storagekws.SetAttribute("user_id", userId)
//Broadcast to all the connected users the newcomerkws.Broadcast([]byte(fmt.Sprintf("New user connected: %s and UUID: %s", userId, kws.UUID)), true, socketio.TextMessage)
//Write welcome messagekws.Emit([]byte(fmt.Sprintf("Hello user: %s with UUID: %s", userId, kws.UUID)), socketio.TextMessage)
}))
log.Fatal(app.Listen(":3000"))
}