Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ndthuan/websocketserver
Standardized WebSocket messages handling in Go
https://github.com/ndthuan/websocketserver
golang websocket websocket-server
Last synced: 3 days ago
JSON representation
Standardized WebSocket messages handling in Go
- Host: GitHub
- URL: https://github.com/ndthuan/websocketserver
- Owner: ndthuan
- Created: 2021-02-22T05:43:49.000Z (almost 4 years ago)
- Default Branch: master
- Last Pushed: 2021-02-26T01:35:17.000Z (almost 4 years ago)
- Last Synced: 2024-11-16T23:14:43.051Z (2 months ago)
- Topics: golang, websocket, websocket-server
- Language: Go
- Homepage:
- Size: 18.6 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# WebSocketServer
WebSocketServer helps you to organize code by introducing a consistent message format. Messages are routed to handlers based on their types.This is a wrapper of the lower level library `gorilla/websocket`.
# Installation
```shell
go get github.com/ndthuan/websocketserver
```
Import:
```go
package mainimport "github.com/ndthuan/websocketserver"
```# Features
* Works with JSON standardized messages
```json
{
"type": "message-type",
"payload": "any kind of string, usually json-encoded"
}
```
* Super easy to use: messages are routed to registered handlers based on message type (think router)
```go
wsServer.On("login", loginHandler())
wsServer.On("logout", logoutHandler())
wsServer.On("human-message", humanMessageHandler())
```
* Ability to broadcast customized messages to all connected clients (see below)
* A standalone runner can be started in a separate goroutine to proactively broadcast messages to all clients without receiving a message
```go
package mainimport (
"github.com/gorilla/websocket"
"github.com/ndthuan/websocketserver"
"time"
)func broadcastMessageBuilder(conn *websocket.Conn) (*websocketserver.Message, bool) {
msg := &websocketserver.Message{
Type: "system-broadcast",
Payload: "Hi, how are you?",
}
return msg, true
}func standaloneRunner() websocketserver.StandaloneRunner {
return func(server *websocketserver.Server) {
for {
time.Sleep(time.Second)server.Broadcast(broadcastMessageBuilder)
}
}
}wsServer.SetStandaloneRunner(standaloneRunner())
```
* Can be integrated with any framework because the underlying library `gorilla/websocket` works with the standard Go HTTP server
* Hooks for connection events
```go
wsServer.OnConnected(connectedCallback())
wsServer.OnDisconnected(disconnectedCallback())
```# Examples
See [a simple chat server](./examples/chat-server/) for an example of how it is used.