Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7457604e0f | |||
| f32d97eac4 | |||
| 4111dd0f25 | |||
| f91e24cc02 | |||
| ef98404caf | |||
| eac2ed2bf1 | |||
| 6b58b7f233 |
20
README.md
20
README.md
@@ -1,2 +1,22 @@
|
|||||||
# safe-web-socket
|
# safe-web-socket
|
||||||
|
|
||||||
|
> A secure, production-ready WebSocket wrapper for Go with built-in validation, rate limiting, authentication, and connection management.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
`SafeWebSocket` is a Go library designed to simplify the creation of **secure, scalable, and resilient WebSocket servers**. Built on top of `gorilla/websocket`, it adds essential safety layers — including authentication, input validation, connection limits, rate limiting, and graceful shutdown — so you can focus on your application logic, not security pitfalls.
|
||||||
|
|
||||||
|
Whether you’re building real-time dashboards, chat apps, or live data feeds, `SafeWebSocket` ensures your WebSocket endpoints are protected against common attacks (e.g., DoS, injection, unauthorized access).
|
||||||
|
|
||||||
|
## Features
|
||||||
|
- ✅ **Graceful Shutdown & Cleanup**
|
||||||
|
- ✅ **Automatic Reconnection Handling (Client-side helpers)**
|
||||||
|
- ✅ **WebSocket Ping/Pong Health Checks**
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go get git.neurocipta.com/rogerferdinan/safe-web-socket
|
||||||
|
```
|
||||||
|
|
||||||
|
> Requires Go 1.24+
|
||||||
2
go.mod
2
go.mod
@@ -3,3 +3,5 @@ module git.neurocipta.com/rogerferdinan/safe-web-socket
|
|||||||
go 1.24.5
|
go 1.24.5
|
||||||
|
|
||||||
require github.com/gorilla/websocket v1.5.3
|
require github.com/gorilla/websocket v1.5.3
|
||||||
|
|
||||||
|
require git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0 // indirect
|
||||||
|
|||||||
2
go.sum
2
go.sum
@@ -1,2 +1,4 @@
|
|||||||
|
git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0 h1:KnNc40SrYsg0cksIIcQy/ca6bunkGADQOs1u7O/E+iY=
|
||||||
|
git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0/go.mod h1:9DvvHc2UZhBwEs63NgO4IhiuHnBNtTuBkTJgiMnnCss=
|
||||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
|
|||||||
189
internal/hub.go
189
internal/hub.go
@@ -8,21 +8,25 @@ import (
|
|||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
writeWait = 10 * time.Second
|
||||||
|
pongWait = 60 * time.Second
|
||||||
|
pingPeriod = 55 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
Conn *websocket.Conn
|
Conn *websocket.Conn
|
||||||
Send chan []byte
|
Send chan []byte
|
||||||
SubscribedPath string
|
SubscribedPath string
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
mu *CustomRwMutex
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewClient(conn *websocket.Conn, subscribedPath string) *Client {
|
func NewClient(conn *websocket.Conn, subscribedPath string) *Client {
|
||||||
return &Client{
|
return &Client{
|
||||||
Conn: conn,
|
Conn: conn,
|
||||||
Send: make(chan []byte, 1024),
|
Send: make(chan []byte, 64),
|
||||||
SubscribedPath: subscribedPath,
|
SubscribedPath: subscribedPath,
|
||||||
done: make(chan struct{}),
|
done: make(chan struct{}),
|
||||||
mu: NewCustomRwMutex(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,9 +35,6 @@ type Hub struct {
|
|||||||
Broadcast chan []byte
|
Broadcast chan []byte
|
||||||
Register chan *Client
|
Register chan *Client
|
||||||
Unregister chan *Client
|
Unregister chan *Client
|
||||||
ClientData map[string]chan []byte
|
|
||||||
writeMu *CustomRwMutex
|
|
||||||
readMu *CustomRwMutex
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHub() *Hub {
|
func NewHub() *Hub {
|
||||||
@@ -42,72 +43,29 @@ func NewHub() *Hub {
|
|||||||
Register: make(chan *Client),
|
Register: make(chan *Client),
|
||||||
Unregister: make(chan *Client),
|
Unregister: make(chan *Client),
|
||||||
Clients: make(map[*Client]bool),
|
Clients: make(map[*Client]bool),
|
||||||
ClientData: make(map[string]chan []byte),
|
|
||||||
writeMu: NewCustomRwMutex(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hub) AddDataChannel(dataID string) chan []byte {
|
|
||||||
ch := make(chan []byte, 256)
|
|
||||||
h.writeMu.WriteHandler(func() error {
|
|
||||||
if innerCh, ok := h.ClientData[dataID]; ok {
|
|
||||||
ch = innerCh
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
h.ClientData[dataID] = ch
|
|
||||||
log.Printf("Created data channel for: %s\n", dataID)
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return ch
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Hub) GetDataChannel(dataID string) (chan []byte, bool) {
|
|
||||||
var ch chan []byte
|
|
||||||
var ok bool
|
|
||||||
h.writeMu.ReadHandler(func() error {
|
|
||||||
innerCh, innerOk := h.ClientData[dataID]
|
|
||||||
ch = innerCh
|
|
||||||
ok = innerOk
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return ch, ok
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Hub) RemoveDataChannel(dataID string) {
|
|
||||||
h.writeMu.WriteHandler(func() error {
|
|
||||||
if ch, ok := h.ClientData[dataID]; ok {
|
|
||||||
close(ch)
|
|
||||||
delete(h.ClientData, dataID)
|
|
||||||
log.Printf("Removed data channel for: %s\n", dataID)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Hub) Run() {
|
func (h *Hub) Run() {
|
||||||
go func() {
|
go func() {
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case c := <-h.Register:
|
case client := <-h.Register:
|
||||||
h.Clients[c] = true
|
h.Clients[client] = true
|
||||||
log.Println("Client registered")
|
log.Println("Client registered")
|
||||||
case c := <-h.Unregister:
|
case c := <-h.Unregister:
|
||||||
if _, ok := h.Clients[c]; ok {
|
if _, ok := h.Clients[c]; ok {
|
||||||
delete(h.Clients, c)
|
delete(h.Clients, c)
|
||||||
close(c.Send)
|
close(c.Send)
|
||||||
c.Conn.Close()
|
|
||||||
log.Println("Client unregistered")
|
|
||||||
}
|
}
|
||||||
|
log.Println("Client Unregistered")
|
||||||
case message := <-h.Broadcast:
|
case message := <-h.Broadcast:
|
||||||
for c := range h.Clients {
|
for client := range h.Clients {
|
||||||
select {
|
select {
|
||||||
case c.Send <- message:
|
case client.Send <- message:
|
||||||
default:
|
default:
|
||||||
close(c.Send)
|
close(client.Send)
|
||||||
delete(h.Clients, c)
|
delete(h.Clients, client)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -116,73 +74,58 @@ func (h *Hub) Run() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func WritePump(c *Client, h *Hub) {
|
func WritePump(c *Client, h *Hub) {
|
||||||
go func() {
|
pingTicker := time.NewTicker(pingPeriod)
|
||||||
defer func() {
|
defer func() {
|
||||||
h.Unregister <- c
|
h.Unregister <- c
|
||||||
c.Conn.Close()
|
pingTicker.Stop()
|
||||||
}()
|
c.Conn.Close()
|
||||||
|
|
||||||
c.Conn.SetReadLimit(1024)
|
|
||||||
c.Conn.SetPongHandler(func(string) error {
|
|
||||||
if err := c.Conn.WriteMessage(websocket.PongMessage, []byte{}); err != nil {
|
|
||||||
return fmt.Errorf("failed to send pong: %v", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
|
|
||||||
ticker := time.NewTicker(30 * time.Second)
|
|
||||||
defer ticker.Stop()
|
|
||||||
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case message, ok := <-c.Send:
|
|
||||||
if err := c.mu.WriteHandler(func() error {
|
|
||||||
if !ok {
|
|
||||||
c.Conn.WriteMessage(websocket.CloseMessage, []byte{})
|
|
||||||
return fmt.Errorf("message not ok")
|
|
||||||
}
|
|
||||||
|
|
||||||
w, err := c.Conn.NextWriter(websocket.TextMessage)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to get writer: %q", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Write(message)
|
|
||||||
|
|
||||||
if err := w.Close(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}); err == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
case <-ticker.C:
|
|
||||||
if err := c.mu.WriteHandler(func() error {
|
|
||||||
if err := c.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func ReadPump(c *Client) {
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
_, message, err := c.Conn.ReadMessage()
|
|
||||||
if err != nil {
|
|
||||||
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
|
|
||||||
log.Printf("WebSocket error: %v", err)
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Println(string(message))
|
|
||||||
}
|
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case message, ok := <-c.Send:
|
||||||
|
c.Conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||||
|
if !ok {
|
||||||
|
c.Conn.WriteMessage(websocket.CloseMessage, []byte{})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.Conn.WriteMessage(websocket.TextMessage, message); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case <-pingTicker.C:
|
||||||
|
c.Conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||||
|
if err := c.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ReadPump(c *Client, h *Hub) {
|
||||||
|
defer func() {
|
||||||
|
h.Unregister <- c
|
||||||
|
c.Conn.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
|
c.Conn.SetReadLimit(512)
|
||||||
|
c.Conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||||
|
c.Conn.SetPongHandler(func(string) error {
|
||||||
|
c.Conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
for {
|
||||||
|
messageType, message, err := c.Conn.ReadMessage()
|
||||||
|
if err != nil {
|
||||||
|
if !websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
|
||||||
|
log.Printf("WebSocket error: %v", err)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if messageType == websocket.TextMessage {
|
||||||
|
fmt.Printf("Received: %s\n", message)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
package internal
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
type CustomRwMutex struct {
|
|
||||||
mu *sync.RWMutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCustomRwMutex() *CustomRwMutex {
|
|
||||||
return &CustomRwMutex{
|
|
||||||
mu: &sync.RWMutex{},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rwMu *CustomRwMutex) WriteHandler(fn func() error) error {
|
|
||||||
rwMu.mu.Lock()
|
|
||||||
defer rwMu.mu.Unlock()
|
|
||||||
if err := fn(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rwMu *CustomRwMutex) ReadHandler(fn func() error) error {
|
|
||||||
rwMu.mu.RLock()
|
|
||||||
defer rwMu.mu.RUnlock()
|
|
||||||
if err := fn(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
223
v1/client/client.go
Normal file
223
v1/client/client.go
Normal file
@@ -0,0 +1,223 @@
|
|||||||
|
package client
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
custom_rwmutex "git.neurocipta.com/rogerferdinan/custom-rwmutex"
|
||||||
|
"git.neurocipta.com/rogerferdinan/safe-web-socket/internal"
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
pingPeriod = 10 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
type SafeWebsocketClientBuilder struct {
|
||||||
|
baseHost *string `nil_checker:"required"`
|
||||||
|
basePort *uint16 `nil_checker:"required"`
|
||||||
|
path *string
|
||||||
|
rawQuery *string
|
||||||
|
useTLS *bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSafeWebsocketClientBuilder() *SafeWebsocketClientBuilder {
|
||||||
|
return &SafeWebsocketClientBuilder{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *SafeWebsocketClientBuilder) BaseHost(host string) *SafeWebsocketClientBuilder {
|
||||||
|
b.baseHost = &host
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *SafeWebsocketClientBuilder) BasePort(port uint16) *SafeWebsocketClientBuilder {
|
||||||
|
b.basePort = &port
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *SafeWebsocketClientBuilder) UseTLS(useTLS bool) *SafeWebsocketClientBuilder {
|
||||||
|
b.useTLS = &useTLS
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *SafeWebsocketClientBuilder) Path(path string) *SafeWebsocketClientBuilder {
|
||||||
|
b.path = &path
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *SafeWebsocketClientBuilder) RawQuery(rawQuery string) *SafeWebsocketClientBuilder {
|
||||||
|
b.rawQuery = &rawQuery
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *SafeWebsocketClientBuilder) Build() (*SafeWebsocketClient, error) {
|
||||||
|
if err := internal.NilChecker(b); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var useTLS bool
|
||||||
|
if b.useTLS != nil {
|
||||||
|
useTLS = *b.useTLS
|
||||||
|
}
|
||||||
|
|
||||||
|
wsClient := SafeWebsocketClient{
|
||||||
|
baseHost: *b.baseHost,
|
||||||
|
basePort: *b.basePort,
|
||||||
|
useTLS: useTLS,
|
||||||
|
path: b.path,
|
||||||
|
rawQuery: b.rawQuery,
|
||||||
|
dataChannel: make(chan []byte, 1),
|
||||||
|
mu: custom_rwmutex.NewCustomRwMutex(),
|
||||||
|
reconnectCh: make(chan struct{}, 1),
|
||||||
|
isConnected: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := wsClient.connect(); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to establish initial connection: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &wsClient, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type SafeWebsocketClient struct {
|
||||||
|
baseHost string
|
||||||
|
basePort uint16
|
||||||
|
useTLS bool
|
||||||
|
path *string
|
||||||
|
rawQuery *string
|
||||||
|
dataChannel chan []byte
|
||||||
|
mu *custom_rwmutex.CustomRwMutex
|
||||||
|
conn *websocket.Conn
|
||||||
|
ctx context.Context
|
||||||
|
cancel context.CancelFunc
|
||||||
|
reconnectCh chan struct{}
|
||||||
|
isConnected bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) connect() error {
|
||||||
|
var scheme string
|
||||||
|
if wsClient.useTLS {
|
||||||
|
scheme = "wss"
|
||||||
|
} else {
|
||||||
|
scheme = "ws"
|
||||||
|
}
|
||||||
|
newURL := url.URL{
|
||||||
|
Scheme: scheme,
|
||||||
|
Host: fmt.Sprintf("%s:%d", wsClient.baseHost, wsClient.basePort),
|
||||||
|
}
|
||||||
|
|
||||||
|
if wsClient.path != nil && strings.TrimSpace(*wsClient.path) != "" {
|
||||||
|
newURL.Path = *wsClient.path
|
||||||
|
}
|
||||||
|
|
||||||
|
if wsClient.rawQuery != nil && strings.TrimSpace(*wsClient.rawQuery) != "" {
|
||||||
|
newURL.RawQuery = *wsClient.rawQuery
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, _, err := websocket.DefaultDialer.Dial(newURL.String(), nil)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to connect to %s: %w", wsClient.baseHost, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
conn.SetPingHandler(func(pingData string) error {
|
||||||
|
if err := conn.WriteMessage(websocket.PongMessage, []byte(pingData)); err != nil {
|
||||||
|
if err == websocket.ErrCloseSent {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if netErr, ok := err.(interface{ Timeout() bool }); ok && netErr.Timeout() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
wsClient.mu.WriteHandler(func() error {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
wsClient.ctx = ctx
|
||||||
|
wsClient.cancel = cancel
|
||||||
|
wsClient.conn = conn
|
||||||
|
wsClient.isConnected = true
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
go wsClient.startPingTicker()
|
||||||
|
go wsClient.startReceiveHandler()
|
||||||
|
go wsClient.reconnectHandler()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) startPingTicker() {
|
||||||
|
ticker := time.NewTicker(pingPeriod)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
wsClient.mu.WriteHandler(func() error {
|
||||||
|
if err := wsClient.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
|
||||||
|
log.Printf("Ping failed: %v. Will attempt reconnect.", err)
|
||||||
|
wsClient.triggerReconnect()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
case <-wsClient.ctx.Done():
|
||||||
|
log.Println("Ping ticker stopped")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) startReceiveHandler() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-wsClient.ctx.Done():
|
||||||
|
log.Println("Reconnect handler stopped")
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
if err := wsClient.mu.ReadHandler(func() error {
|
||||||
|
conn := wsClient.conn
|
||||||
|
|
||||||
|
if conn == nil {
|
||||||
|
return fmt.Errorf("no active connection, waiting for reconnect")
|
||||||
|
}
|
||||||
|
_, message, err := conn.ReadMessage()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
wsClient.dataChannel <- message
|
||||||
|
return nil
|
||||||
|
}); err != nil {
|
||||||
|
wsClient.triggerReconnect()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) triggerReconnect() {
|
||||||
|
select {
|
||||||
|
case wsClient.reconnectCh <- struct{}{}:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) reconnectHandler() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-wsClient.reconnectCh:
|
||||||
|
wsClient.cancel()
|
||||||
|
wsClient.connect()
|
||||||
|
case <-wsClient.ctx.Done():
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) DataChannel() <-chan []byte {
|
||||||
|
return wsClient.dataChannel
|
||||||
|
}
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.neurocipta.com/rogerferdinan/safe-web-socket/v1/server"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
s, err := server.NewSafeWebsocketServerBuilder().
|
|
||||||
BaseHost("localhost").
|
|
||||||
BasePort(8080).
|
|
||||||
HandleFuncWebsocket("/ws/test/", "data_1", func(c chan []byte) {
|
|
||||||
ticker := time.NewTicker(100 * time.Millisecond)
|
|
||||||
for range ticker.C {
|
|
||||||
c <- []byte(time.Now().Format("2006-01-02 15:04:05") + "_data_1")
|
|
||||||
}
|
|
||||||
}).
|
|
||||||
HandleFuncWebsocket("/ws/test/", "data_2", func(c chan []byte) {
|
|
||||||
ticker := time.NewTicker(100 * time.Millisecond)
|
|
||||||
for range ticker.C {
|
|
||||||
c <- []byte(time.Now().Format("2006-01-02 15:04:05") + "_data_2")
|
|
||||||
}
|
|
||||||
}).
|
|
||||||
Build()
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
s.ListenAndServe()
|
|
||||||
}
|
|
||||||
25
v1/examples/client/main.go
Normal file
25
v1/examples/client/main.go
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"git.neurocipta.com/rogerferdinan/safe-web-socket/v1/client"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
wsClient, err := client.NewSafeWebsocketClientBuilder().
|
||||||
|
BaseHost("localhost").
|
||||||
|
BasePort(8080).
|
||||||
|
Path("/ws/test/data_1").
|
||||||
|
UseTLS(false).
|
||||||
|
Build()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
dataChannel := wsClient.DataChannel()
|
||||||
|
|
||||||
|
for data := range dataChannel {
|
||||||
|
fmt.Println(string(data))
|
||||||
|
}
|
||||||
|
}
|
||||||
52
v1/examples/server/main.go
Normal file
52
v1/examples/server/main.go
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.neurocipta.com/rogerferdinan/safe-web-socket/v1/server"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ExampleData struct {
|
||||||
|
Time time.Time `json:"time"`
|
||||||
|
Data string `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
s, err := server.NewSafeWebsocketServerBuilder().
|
||||||
|
BaseHost("localhost").
|
||||||
|
BasePort(8080).
|
||||||
|
HandleFuncWebsocket("/ws/test/", "data_1", func(c chan []byte) {
|
||||||
|
ticker := time.NewTicker(10 * time.Millisecond)
|
||||||
|
for range ticker.C {
|
||||||
|
jsonBytes, err := json.Marshal(ExampleData{
|
||||||
|
Time: time.Now(),
|
||||||
|
Data: "data_1",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
c <- jsonBytes
|
||||||
|
}
|
||||||
|
}).
|
||||||
|
HandleFuncWebsocket("/ws/test/", "data_2", func(c chan []byte) {
|
||||||
|
ticker := time.NewTicker(10 * time.Millisecond)
|
||||||
|
for range ticker.C {
|
||||||
|
jsonBytes, err := json.Marshal(ExampleData{
|
||||||
|
Time: time.Now(),
|
||||||
|
Data: "data_2",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
c <- jsonBytes
|
||||||
|
}
|
||||||
|
}).
|
||||||
|
Build()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
s.ListenAndServe()
|
||||||
|
}
|
||||||
@@ -18,9 +18,6 @@ type SafeWebsocketServerBuilder struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewSafeWebsocketServerBuilder() *SafeWebsocketServerBuilder {
|
func NewSafeWebsocketServerBuilder() *SafeWebsocketServerBuilder {
|
||||||
h := internal.NewHub()
|
|
||||||
h.Run()
|
|
||||||
|
|
||||||
return &SafeWebsocketServerBuilder{
|
return &SafeWebsocketServerBuilder{
|
||||||
upgrader: &websocket.Upgrader{
|
upgrader: &websocket.Upgrader{
|
||||||
ReadBufferSize: 1024,
|
ReadBufferSize: 1024,
|
||||||
@@ -64,16 +61,15 @@ func (b *SafeWebsocketServerBuilder) HandleFuncWebsocket(
|
|||||||
}
|
}
|
||||||
|
|
||||||
subscribedPath := strings.TrimPrefix(r.URL.Path, pattern)
|
subscribedPath := strings.TrimPrefix(r.URL.Path, pattern)
|
||||||
fmt.Println(subscribedPath)
|
|
||||||
if subscribedPath == "" {
|
if subscribedPath == "" {
|
||||||
http.Error(w, "invalid path", http.StatusBadRequest)
|
http.Error(w, "invalid path", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c := internal.NewClient(conn, subscribedPath)
|
c := internal.NewClient(conn, subscribedPath)
|
||||||
h.Register <- c
|
h.Register <- c
|
||||||
internal.WritePump(c, h)
|
go internal.WritePump(c, h)
|
||||||
internal.ReadPump(c)
|
go internal.ReadPump(c, h)
|
||||||
writeFunc(h.Broadcast)
|
go writeFunc(h.Broadcast)
|
||||||
})
|
})
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
@@ -86,7 +82,6 @@ func (b *SafeWebsocketServerBuilder) Build() (*SafeWebsocketServer, error) {
|
|||||||
safeServer := SafeWebsocketServer{
|
safeServer := SafeWebsocketServer{
|
||||||
url: fmt.Sprintf("%s:%d", *b.baseHost, *b.basePort),
|
url: fmt.Sprintf("%s:%d", *b.baseHost, *b.basePort),
|
||||||
mux: b.mux,
|
mux: b.mux,
|
||||||
mu: internal.NewCustomRwMutex(),
|
|
||||||
}
|
}
|
||||||
return &safeServer, nil
|
return &safeServer, nil
|
||||||
}
|
}
|
||||||
@@ -95,7 +90,6 @@ type SafeWebsocketServer struct {
|
|||||||
hub *internal.Hub
|
hub *internal.Hub
|
||||||
mux *http.ServeMux
|
mux *http.ServeMux
|
||||||
url string
|
url string
|
||||||
mu *internal.CustomRwMutex
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *SafeWebsocketServer) ListenAndServe() error {
|
func (s *SafeWebsocketServer) ListenAndServe() error {
|
||||||
|
|||||||
Reference in New Issue
Block a user