package main
import (
"encoding/json""fmt"
ikisocket "github.com/antoniodipinto/ikisocket""github.com/gofiber/fiber/v2"
)
// Basic chat message objecttypeMessageObjectstruct {
Datastring`json:"data"`Fromstring`json:"from"`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) {
c.Locals("user_id", c.Query("user_id"))
c.Next()
})
// Multiple event handling supportedikisocket.On(ikisocket.EventConnect, func(ep*ikisocket.EventPayload) {
fmt.Println("fired connect 1")
})
ikisocket.On(ikisocket.EventConnect, func(ep*ikisocket.EventPayload) {
fmt.Println("fired connect 2")
})
ikisocket.On(ikisocket.EventMessage, func(ep*ikisocket.EventPayload) {
fmt.Println("fired message: "+string(ep.Data))
})
ikisocket.On(ikisocket.EventDisconnect, func(ep*ikisocket.EventPayload) {
fmt.Println("fired disconnect"+ep.Error.Error())
})
// Websocket route initapp.Get("/ws", ikisocket.New(func(kws*ikisocket.Websocket) {
// Retrieve user id from the middleware (optional)userId:=fmt.Sprintf("%v", kws.Locals("user_id"))
// Every websocket connection has an optional session key => value storagekws.SetAttribute("user_id", userId)
// On connect event. Notify when comes a new connectionkws.OnConnect=func() {
// Add the connection to the list of the connected clients// The UUID is generated randomlyclients[userId] =kws.UUID//Broadcast to all the connected users the newcomerkws.Broadcast([]byte("New user connected: "+userId+" and UUID: "+kws.UUID), true)
//Write welcome messagekws.Emit([]byte("Hello user: "+userId+" and UUID: "+kws.UUID))
}
// On message eventkws.OnMessage=func(data []byte) {
message:=MessageObject{}
json.Unmarshal(data, &message)
// Emit the message directly to specified usererr:=kws.EmitTo(clients[message.To], data)
iferr!=nil {
fmt.Println(err)
}
}
}))
ikisocket.On("close", func(payload*ikisocket.EventPayload) {
fmt.Println("fired close "+payload.SocketAttributes["user_id"])
})
// Start the application on port 3000app.Listen(3000)
}
Connect to the websocket
ws://localhost:3000/ws?user_id=54s5f18d1h8d1h8f
About
🧬 WebSocket wrapper with event management for Fiber https://github.com/gofiber/fiber. Based on Fiber WebSocket and inspired by Socket.io