WebSocket Manager is a Go library that simplifies managing WebSocket connections. It offers functionalities like upgrading HTTP connections to WebSocket, managing clients, broadcasting messages, and more.
This library is an abstraction on top of the gorilla/websocket library.
Install the package using go get
:
go get github.com/NotCoffee418/websocketmanager
Add the package to your code:
import "github.com/NotCoffee418/websocketmanager"
Here's how to use WebSocket Manager in your Go application.
Create a new instance of the Manager type using one of the following methods:
// Create a manager with default settings
wsManager := websocketmanager.NewDefaultManager()
// Create a manager with customized settings
wsManager := websocketmanager.NewBuilder().
WithReadBufferSize(2048).
WithWriteBufferSize(2048).
WithClientCleanupDisabled().
Build()
Upgrade an incoming HTTP request to a WebSocket connection:
func ginHandler(c *gin.Context) {
wsClient <- wsManager.UpgradeClient(c.Writer, c.Request)
//...
}
This library is agnostic to the specific Go web framework used, as long as the framework is based on Go's standard net/http
package.
To categorize clients into groups, use the AssignGroups
method:
wsManager.AssignGroups(*client.ConnId, 1, 2)
To observe messages from a specific client, register an observer function:
wsManager.RegisterClientObserver(*client.ConnId, func(wsClient *websocketmanager.Client, messageType int, message []byte) {
// Handle incoming message
})
To send messages, you have the following options:
-
Broadcast a message to all clients
wsManager.BroadcastMessage(messageType, message)
-
Send a message to a specific group of clients
wsManager.SendMessageToGroup(groupID, messageType, message)
-
Send a message to a specific client
wsManager.SendMessageToUser(clientUUID, messageType, message)
Message type definitions can be found in the gorilla/websocket library.
messageType := websocket.TextMessage
You can manually unregister clients or retrieve specific clients by their UUID:
-
To unregister a client:
wsManager.Unregister(clientUUID)
-
To get a specific client:
client, err := wsManager.GetWebSocketClient(clientUUID)
By default, WebSocket Manager will automatically clean up inactive clients. You can disable this during the initialization step if needed.
Contributions are welcome. Feel free to open a pull request or issue on GitHub.
This project is licensed under the MIT License.
For more information, please refer to the LICENSE file in the repository.