Compare commits
36 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cd4a239f14 | |||
| 0d0de32d21 | |||
| 88ae539f54 | |||
| 78a5b21531 | |||
| e011931436 | |||
| 70d9a37a4e | |||
| 2ab2e07b9b | |||
| 9a9c65c24c | |||
| 8a11ce0103 | |||
| cf63683c9c | |||
| 92bd56aac0 | |||
| b4e7238b0b | |||
| b092e36987 | |||
| 4f956b8fe9 | |||
| 967b8a98b3 | |||
| d09d389011 | |||
| c550701dfa | |||
| 2225391fc3 | |||
| 9f8ee49b5c | |||
| 735f55858e | |||
| 5e5df9090f | |||
| 1537e58444 | |||
| 66b27082b9 | |||
| 9d74e72ede | |||
| dfbe2f2808 | |||
| 4792d638c1 | |||
| b96e574726 | |||
| 752804cc58 | |||
| e686e69a24 | |||
| 034e5b68e0 | |||
| 6fb7cea1fa | |||
| 7457604e0f | |||
| f32d97eac4 | |||
| 4111dd0f25 | |||
| f91e24cc02 | |||
| ef98404caf |
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+
|
||||||
4
go.mod
4
go.mod
@@ -3,3 +3,7 @@ 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
|
||||||
|
|
||||||
|
require git.neurocipta.com/rogerferdinan/safe-map v0.0.0-20251011004629-ab0b119a7c48 // indirect
|
||||||
|
|||||||
4
go.sum
4
go.sum
@@ -1,2 +1,6 @@
|
|||||||
|
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=
|
||||||
|
git.neurocipta.com/rogerferdinan/safe-map v0.0.0-20251011004629-ab0b119a7c48 h1:4wXSbEuwFd2gycaaGP35bjUkKEEO6WcVfJ6cetEyT5s=
|
||||||
|
git.neurocipta.com/rogerferdinan/safe-map v0.0.0-20251011004629-ab0b119a7c48/go.mod h1:QtIxG0BYCCq8a5qyklpSHA8qWUvKr+mfl42qF9QxTc0=
|
||||||
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=
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package internal
|
package internal
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"log"
|
"log"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -11,7 +10,7 @@ import (
|
|||||||
const (
|
const (
|
||||||
writeWait = 10 * time.Second
|
writeWait = 10 * time.Second
|
||||||
pongWait = 60 * time.Second
|
pongWait = 60 * time.Second
|
||||||
pingPeriod = 55 * time.Second
|
pingPeriod = 25 * time.Second
|
||||||
)
|
)
|
||||||
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
@@ -19,16 +18,14 @@ type Client struct {
|
|||||||
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, 64),
|
Send: make(chan []byte, 2),
|
||||||
SubscribedPath: subscribedPath,
|
SubscribedPath: subscribedPath,
|
||||||
done: make(chan struct{}),
|
done: make(chan struct{}, 1),
|
||||||
mu: NewCustomRwMutex(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,17 +34,14 @@ type Hub struct {
|
|||||||
Broadcast chan []byte
|
Broadcast chan []byte
|
||||||
Register chan *Client
|
Register chan *Client
|
||||||
Unregister chan *Client
|
Unregister chan *Client
|
||||||
writeMu *CustomRwMutex
|
|
||||||
readMu *CustomRwMutex
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHub() *Hub {
|
func NewHub() *Hub {
|
||||||
return &Hub{
|
return &Hub{
|
||||||
Broadcast: make(chan []byte),
|
Broadcast: make(chan []byte, 1),
|
||||||
Register: make(chan *Client),
|
Register: make(chan *Client, 1),
|
||||||
Unregister: make(chan *Client),
|
Unregister: make(chan *Client, 1),
|
||||||
Clients: make(map[*Client]bool),
|
Clients: make(map[*Client]bool, 1),
|
||||||
writeMu: NewCustomRwMutex(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,6 +57,7 @@ func (h *Hub) Run() {
|
|||||||
delete(h.Clients, c)
|
delete(h.Clients, c)
|
||||||
close(c.Send)
|
close(c.Send)
|
||||||
}
|
}
|
||||||
|
log.Println("Client Unregistered")
|
||||||
case message := <-h.Broadcast:
|
case message := <-h.Broadcast:
|
||||||
for client := range h.Clients {
|
for client := range h.Clients {
|
||||||
select {
|
select {
|
||||||
@@ -99,7 +94,7 @@ func WritePump(c *Client, h *Hub) {
|
|||||||
}
|
}
|
||||||
case <-pingTicker.C:
|
case <-pingTicker.C:
|
||||||
c.Conn.SetWriteDeadline(time.Now().Add(writeWait))
|
c.Conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||||
if err := c.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {
|
if err := c.Conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -129,7 +124,7 @@ func ReadPump(c *Client, h *Hub) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if messageType == websocket.TextMessage {
|
if messageType == websocket.TextMessage {
|
||||||
fmt.Printf("Received: %s\n", message)
|
log.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
|
|
||||||
}
|
|
||||||
@@ -1,82 +1,458 @@
|
|||||||
package client
|
package client
|
||||||
|
|
||||||
// import (
|
import (
|
||||||
// "context"
|
"context"
|
||||||
// "fmt"
|
"fmt"
|
||||||
// "time"
|
"log"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
// "git.neurocipta.com/rogerferdinan/safe-web-socket/internal"
|
custom_rwmutex "git.neurocipta.com/rogerferdinan/custom-rwmutex"
|
||||||
// "github.com/gorilla/websocket"
|
safemap "git.neurocipta.com/rogerferdinan/safe-map"
|
||||||
// )
|
"git.neurocipta.com/rogerferdinan/safe-web-socket/internal"
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
)
|
||||||
|
|
||||||
// const (
|
const (
|
||||||
// pingPeriod = 30 * time.Second
|
pingPeriod = 10 * time.Second
|
||||||
// )
|
readDeadline = 30 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
// type SafeWebsocketClientBuilder struct {
|
type MessageType uint
|
||||||
// baseHost *string `nil_checker:"required"`
|
|
||||||
// basePort *uint16 `nil_checker:"required"`
|
|
||||||
// }
|
|
||||||
|
|
||||||
// func NewSafeWebsocketClientBuilder() *SafeWebsocketClientBuilder {
|
const (
|
||||||
// return &SafeWebsocketClientBuilder{}
|
MessageTypeText MessageType = websocket.TextMessage
|
||||||
// }
|
MessageTypePing MessageType = websocket.PingMessage
|
||||||
|
MessageTypePong MessageType = websocket.PongMessage
|
||||||
|
MessageTypeClose MessageType = websocket.CloseMessage
|
||||||
|
)
|
||||||
|
|
||||||
// func (b *SafeWebsocketClientBuilder) BaseHost(host string) *SafeWebsocketClientBuilder {
|
type Message struct {
|
||||||
// b.baseHost = &host
|
MessageType MessageType
|
||||||
// return b
|
Data []byte
|
||||||
// }
|
}
|
||||||
|
|
||||||
// func (b *SafeWebsocketClientBuilder) BasePort(port uint16) *SafeWebsocketClientBuilder {
|
type SafeWebsocketClientBuilder struct {
|
||||||
// b.basePort = &port
|
baseHost *string `nil_checker:"required"`
|
||||||
// return b
|
basePort *uint16 `nil_checker:"required"`
|
||||||
// }
|
path *string
|
||||||
|
rawQuery *string
|
||||||
|
isDrop *bool
|
||||||
|
useTLS *bool
|
||||||
|
channelSize *int64
|
||||||
|
}
|
||||||
|
|
||||||
// func (b *SafeWebsocketClientBuilder) Build() (*SafeWebsocketClient, error) {
|
func NewSafeWebsocketClientBuilder() *SafeWebsocketClientBuilder {
|
||||||
// if err := internal.NilChecker(b); err != nil {
|
return &SafeWebsocketClientBuilder{}
|
||||||
// return nil, err
|
}
|
||||||
// }
|
|
||||||
|
|
||||||
// ctx, cancel := context.WithCancel(context.Background())
|
func (b *SafeWebsocketClientBuilder) BaseHost(host string) *SafeWebsocketClientBuilder {
|
||||||
|
b.baseHost = &host
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
// wsClient := SafeWebsocketClient{
|
func (b *SafeWebsocketClientBuilder) BasePort(port uint16) *SafeWebsocketClientBuilder {
|
||||||
// baseHost: b.baseHost,
|
b.basePort = &port
|
||||||
// basePort: b.basePort,
|
return b
|
||||||
// ctx: ctx,
|
}
|
||||||
// cancel: cancel,
|
|
||||||
// reconnectCh: make(chan struct{}, 1),
|
|
||||||
// isConnected: false,
|
|
||||||
// }
|
|
||||||
|
|
||||||
// if err := wsClient.connect(); err != nil {
|
func (b *SafeWebsocketClientBuilder) UseTLS(useTLS bool) *SafeWebsocketClientBuilder {
|
||||||
// cancel()
|
b.useTLS = &useTLS
|
||||||
// return nil, fmt.Errorf("failed to establish initial connection: %v", err)
|
return b
|
||||||
// }
|
}
|
||||||
|
|
||||||
// wsClient.startPingTicker()
|
func (b *SafeWebsocketClientBuilder) Path(path string) *SafeWebsocketClientBuilder {
|
||||||
// wsClient.startReceiveHandler()
|
b.path = &path
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
// return &wsClient, nil
|
func (b *SafeWebsocketClientBuilder) RawQuery(rawQuery string) *SafeWebsocketClientBuilder {
|
||||||
// }
|
b.rawQuery = &rawQuery
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
// type SafeWebsocketClient struct {
|
func (b *SafeWebsocketClientBuilder) IsDrop(isDrop bool) *SafeWebsocketClientBuilder {
|
||||||
// baseHost *string
|
b.isDrop = &isDrop
|
||||||
// basePort *uint16
|
return b
|
||||||
// mu *internal.CustomRwMutex
|
}
|
||||||
// ctx context.Context
|
|
||||||
// cancel context.CancelFunc
|
|
||||||
// reconnectCh chan struct{}
|
|
||||||
// isConnected bool
|
|
||||||
// }
|
|
||||||
|
|
||||||
// func (wsClient *SafeWebsocketClient) connect() error {
|
func (b *SafeWebsocketClientBuilder) ChannelSize(channelSize int64) *SafeWebsocketClientBuilder {
|
||||||
// url := fmt.Sprintf("%s:%d", *wsClient.baseHost, *wsClient.basePort)
|
b.channelSize = &channelSize
|
||||||
// conn, _, err := websocket.DefaultDialer.Dial(url, nil)
|
return b
|
||||||
// if err != nil {
|
}
|
||||||
// return fmt.Errorf("failed to connect to %s: %w", *wsClient.baseHost, err)
|
|
||||||
// }
|
|
||||||
|
|
||||||
// conn.SetPingHandler(func(pingData string) error {
|
func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketClient, error) {
|
||||||
// conn.WriteMessage(websocket.PongMessage, []byte(pingData))
|
if err := internal.NilChecker(b); err != nil {
|
||||||
// })
|
return nil, err
|
||||||
// }
|
}
|
||||||
|
|
||||||
|
// var useTLS bool
|
||||||
|
if b.useTLS == nil {
|
||||||
|
useTLS := true
|
||||||
|
b.useTLS = &useTLS
|
||||||
|
}
|
||||||
|
|
||||||
|
if b.isDrop == nil {
|
||||||
|
isDrop := true
|
||||||
|
b.isDrop = &isDrop
|
||||||
|
}
|
||||||
|
|
||||||
|
if b.channelSize == nil {
|
||||||
|
channelSize := int64(1)
|
||||||
|
b.channelSize = &channelSize
|
||||||
|
}
|
||||||
|
|
||||||
|
wsClient := SafeWebsocketClient{
|
||||||
|
baseHost: *b.baseHost,
|
||||||
|
basePort: *b.basePort,
|
||||||
|
useTLS: *b.useTLS,
|
||||||
|
isDrop: *b.isDrop,
|
||||||
|
path: b.path,
|
||||||
|
rawQuery: b.rawQuery,
|
||||||
|
dataChannel: make(chan []byte, *b.channelSize),
|
||||||
|
mu: custom_rwmutex.NewCustomRwMutex(),
|
||||||
|
ctx: ctx,
|
||||||
|
reconnectCh: make(chan struct{}, 1),
|
||||||
|
isConnected: false,
|
||||||
|
doneMap: safemap.NewSafeMap[string, chan struct{}](),
|
||||||
|
writeChan: make(chan Message, 1),
|
||||||
|
}
|
||||||
|
|
||||||
|
go wsClient.reconnectHandler()
|
||||||
|
|
||||||
|
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
|
||||||
|
isDrop bool
|
||||||
|
useTLS bool
|
||||||
|
path *string
|
||||||
|
rawQuery *string
|
||||||
|
|
||||||
|
mu *custom_rwmutex.CustomRwMutex
|
||||||
|
conn *websocket.Conn
|
||||||
|
ctx context.Context
|
||||||
|
cancelFuncs []context.CancelFunc
|
||||||
|
dataChannel chan []byte
|
||||||
|
|
||||||
|
reconnectCh chan struct{}
|
||||||
|
reconnectChans []chan struct{}
|
||||||
|
isConnected bool
|
||||||
|
doneMap *safemap.SafeMap[string, chan struct{}]
|
||||||
|
|
||||||
|
writeChan chan Message
|
||||||
|
pongChan chan error
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
pingCtx, pingCancel := context.WithCancel(context.Background())
|
||||||
|
wsClient.mu.WriteHandler(func() error {
|
||||||
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, pingCancel)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
go wsClient.startPingTicker(pingCtx)
|
||||||
|
|
||||||
|
if wsClient.conn != nil {
|
||||||
|
wsClient.conn.Close()
|
||||||
|
}
|
||||||
|
wsClient.conn = conn
|
||||||
|
wsClient.isConnected = true
|
||||||
|
|
||||||
|
go wsClient.writePump()
|
||||||
|
go wsClient.readPump()
|
||||||
|
|
||||||
|
conn.SetPingHandler(func(pingData string) error {
|
||||||
|
wsClient.writeChan <- Message{
|
||||||
|
MessageType: MessageTypePong,
|
||||||
|
Data: []byte(pingData),
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err := <-wsClient.pongChan:
|
||||||
|
return err
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) writePump() {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
wsClient.mu.WriteHandler(func() error {
|
||||||
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, cancel)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
var c *websocket.Conn
|
||||||
|
wsClient.mu.ReadHandler(func() error {
|
||||||
|
c = wsClient.conn
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
log.Println("Writer canceled by context")
|
||||||
|
return
|
||||||
|
case data := <-wsClient.writeChan:
|
||||||
|
if c == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.WriteMessage(int(data.MessageType), data.Data); err != nil {
|
||||||
|
log.Printf("error on write message: %v\n", err)
|
||||||
|
if data.MessageType == MessageTypePong {
|
||||||
|
wsClient.pongChan <- err
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) readPump() {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
wsClient.mu.WriteHandler(func() error {
|
||||||
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, cancel)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
var c *websocket.Conn
|
||||||
|
wsClient.mu.ReadHandler(func() error {
|
||||||
|
c = wsClient.conn
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if wsClient.isDrop {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
log.Println("Reader canceled by context")
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
if c == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.SetReadDeadline(time.Now().Add(readDeadline)); err != nil {
|
||||||
|
log.Printf("error on read deadline: %v\n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
messageType, data, err := c.ReadMessage()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("error on read message: %v\n", err)
|
||||||
|
wsClient.triggerReconnect()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if messageType != websocket.TextMessage {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case wsClient.dataChannel <- data:
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
log.Println("Data channel full, dropping message")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
log.Println("Reader canceled by context")
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
if c == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.SetReadDeadline(time.Now().Add(readDeadline)); err != nil {
|
||||||
|
log.Printf("error on read deadline: %v\n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
messageType, data, err := c.ReadMessage()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("error on read message: %v\n", err)
|
||||||
|
wsClient.triggerReconnect()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if messageType != websocket.TextMessage {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case wsClient.dataChannel <- data:
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) startPingTicker(ctx context.Context) {
|
||||||
|
ticker := time.NewTicker(pingPeriod)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
log.Println("ping ticker stopped")
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
wsClient.writeChan <- Message{
|
||||||
|
MessageType: websocket.PingMessage,
|
||||||
|
Data: []byte{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) triggerReconnect() {
|
||||||
|
select {
|
||||||
|
case wsClient.reconnectCh <- struct{}{}:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) reconnectHandler() {
|
||||||
|
backoff := 1 * time.Second
|
||||||
|
maxBackoff := 30 * time.Second
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-wsClient.reconnectCh:
|
||||||
|
log.Println("Reconnect triggered")
|
||||||
|
|
||||||
|
wsClient.mu.ReadHandler(func() error {
|
||||||
|
if wsClient.cancelFuncs != nil {
|
||||||
|
for _, cancel := range wsClient.cancelFuncs {
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
wsClient.isConnected = false
|
||||||
|
// time.Sleep(100 * time.Millisecond)
|
||||||
|
|
||||||
|
isInnerLoop := true
|
||||||
|
for isInnerLoop {
|
||||||
|
log.Printf("Attempting reconnect in %v...", backoff)
|
||||||
|
select {
|
||||||
|
case <-time.After(backoff):
|
||||||
|
if err := wsClient.connect(); err != nil {
|
||||||
|
log.Printf("Reconnect failed: %v", err)
|
||||||
|
if backoff < maxBackoff {
|
||||||
|
backoff *= 2
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
log.Println("Reconnected successfully")
|
||||||
|
backoff = 1 * time.Second
|
||||||
|
isInnerLoop = false
|
||||||
|
continue
|
||||||
|
case <-wsClient.ctx.Done():
|
||||||
|
log.Println("reconnect handler stopped due to client shutdown")
|
||||||
|
wsClient.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if wsClient.reconnectChans != nil {
|
||||||
|
for _, reconnectCh := range wsClient.reconnectChans {
|
||||||
|
reconnectCh <- struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case <-wsClient.ctx.Done():
|
||||||
|
log.Println("reconnect handler stopped due to client shutdown")
|
||||||
|
wsClient.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) ReconnectChannel() <-chan struct{} {
|
||||||
|
reconnectCh := make(chan struct{}, 1)
|
||||||
|
wsClient.mu.WriteHandler(func() error {
|
||||||
|
wsClient.reconnectChans = append(wsClient.reconnectChans, reconnectCh)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return reconnectCh
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) DataChannel() <-chan []byte {
|
||||||
|
return wsClient.dataChannel
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) Write(data []byte) error {
|
||||||
|
wsClient.writeChan <- Message{
|
||||||
|
MessageType: MessageTypeText,
|
||||||
|
Data: data,
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) Close() error {
|
||||||
|
wsClient.mu.ReadHandler(func() error {
|
||||||
|
if wsClient.cancelFuncs != nil {
|
||||||
|
for _, cancel := range wsClient.cancelFuncs {
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if wsClient.reconnectChans != nil {
|
||||||
|
for _, reconnectChan := range wsClient.reconnectChans {
|
||||||
|
close(reconnectChan)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if wsClient.conn != nil {
|
||||||
|
wsClient.conn.Close()
|
||||||
|
}
|
||||||
|
wsClient.isConnected = false
|
||||||
|
// close(wsClient.dataChannel)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
50
v1/examples/client/main.go
Normal file
50
v1/examples/client/main.go
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"git.neurocipta.com/rogerferdinan/safe-web-socket/v1/client"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
sigChan := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
<-sigChan
|
||||||
|
fmt.Println("\nReceived interrupt signal. Shutting down gracefully...")
|
||||||
|
cancel()
|
||||||
|
}()
|
||||||
|
|
||||||
|
wsClient, err := client.NewSafeWebsocketClientBuilder().
|
||||||
|
BaseHost("localhost").
|
||||||
|
BasePort(8080).
|
||||||
|
Path("/ws/test/data_1").
|
||||||
|
UseTLS(false).
|
||||||
|
ChannelSize(30).
|
||||||
|
Build(ctx)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
for range wsClient.ReconnectChannel() {
|
||||||
|
fmt.Println("Reconnection Success")
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
dataChannel := wsClient.DataChannel()
|
||||||
|
|
||||||
|
for data := range dataChannel {
|
||||||
|
// _ = data
|
||||||
|
fmt.Println(string(data))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,18 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"log"
|
"log"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.neurocipta.com/rogerferdinan/safe-web-socket/v1/server"
|
"git.neurocipta.com/rogerferdinan/safe-web-socket/v1/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type ExampleData struct {
|
||||||
|
Time time.Time `json:"time"`
|
||||||
|
Data string `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
s, err := server.NewSafeWebsocketServerBuilder().
|
s, err := server.NewSafeWebsocketServerBuilder().
|
||||||
BaseHost("localhost").
|
BaseHost("localhost").
|
||||||
@@ -14,13 +20,27 @@ func main() {
|
|||||||
HandleFuncWebsocket("/ws/test/", "data_1", func(c chan []byte) {
|
HandleFuncWebsocket("/ws/test/", "data_1", func(c chan []byte) {
|
||||||
ticker := time.NewTicker(10 * time.Millisecond)
|
ticker := time.NewTicker(10 * time.Millisecond)
|
||||||
for range ticker.C {
|
for range ticker.C {
|
||||||
c <- []byte(time.Now().Format("2006-01-02 15:04:05") + "_data_1")
|
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) {
|
HandleFuncWebsocket("/ws/test/", "data_2", func(c chan []byte) {
|
||||||
ticker := time.NewTicker(10 * time.Millisecond)
|
ticker := time.NewTicker(10 * time.Millisecond)
|
||||||
for range ticker.C {
|
for range ticker.C {
|
||||||
c <- []byte(time.Now().Format("2006-01-02 15:04:05") + "_data_2")
|
jsonBytes, err := json.Marshal(ExampleData{
|
||||||
|
Time: time.Now(),
|
||||||
|
Data: "data_2",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
c <- jsonBytes
|
||||||
}
|
}
|
||||||
}).
|
}).
|
||||||
Build()
|
Build()
|
||||||
@@ -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,
|
||||||
|
|||||||
Reference in New Issue
Block a user