Compare commits
43 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7f21b733ed | |||
| 9816426780 | |||
| 4fc0c438c8 | |||
| 49a30d3b44 | |||
| b71e8121e2 | |||
| 9c6db30550 | |||
| bc2017e67d | |||
| 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
|
||||
|
||||
> 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+
|
||||
15
go.mod
15
go.mod
@@ -3,3 +3,18 @@ module git.neurocipta.com/rogerferdinan/safe-web-socket
|
||||
go 1.24.5
|
||||
|
||||
require github.com/gorilla/websocket v1.5.3
|
||||
|
||||
require (
|
||||
git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0
|
||||
github.com/google/uuid v1.6.0
|
||||
)
|
||||
|
||||
require (
|
||||
git.neurocipta.com/rogerferdinan/safe-map v0.0.0-20251011004629-ab0b119a7c48
|
||||
github.com/gobwas/ws v1.4.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/gobwas/httphead v0.1.0 // indirect
|
||||
github.com/gobwas/pool v0.2.1 // indirect
|
||||
)
|
||||
|
||||
13
go.sum
13
go.sum
@@ -1,2 +1,15 @@
|
||||
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/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
|
||||
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
|
||||
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
|
||||
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
|
||||
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
|
||||
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
|
||||
56
internal/error_response.go
Normal file
56
internal/error_response.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type StatusMessageBuilder struct {
|
||||
statusCode *int
|
||||
message *string
|
||||
}
|
||||
|
||||
func NewStatusMessage() *StatusMessageBuilder {
|
||||
return &StatusMessageBuilder{}
|
||||
}
|
||||
|
||||
func (sm *StatusMessageBuilder) StatusCode(statusCode int) *StatusMessageBuilder {
|
||||
sm.statusCode = &statusCode
|
||||
return sm
|
||||
}
|
||||
|
||||
func (sm *StatusMessageBuilder) Message(message string) *StatusMessageBuilder {
|
||||
sm.message = &message
|
||||
return sm
|
||||
}
|
||||
|
||||
func (sm *StatusMessageBuilder) Build() *StatusMessage {
|
||||
return &StatusMessage{
|
||||
StatusCode: sm.statusCode,
|
||||
Message: sm.message,
|
||||
}
|
||||
}
|
||||
|
||||
type StatusMessage struct {
|
||||
StatusCode *int
|
||||
Message *string `json:"msg"`
|
||||
}
|
||||
|
||||
func ErrorResponse(w http.ResponseWriter, statusMessage *StatusMessage) error {
|
||||
if statusMessage.StatusCode == nil {
|
||||
return fmt.Errorf("status code is missing")
|
||||
}
|
||||
if statusMessage.Message == nil {
|
||||
return fmt.Errorf("message is missing")
|
||||
}
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
w.WriteHeader(*statusMessage.StatusCode)
|
||||
|
||||
b, err := json.Marshal(statusMessage)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal JSON")
|
||||
}
|
||||
w.Write(b)
|
||||
return nil
|
||||
}
|
||||
@@ -5,30 +5,31 @@ import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
const (
|
||||
writeWait = 10 * time.Second
|
||||
pongWait = 60 * time.Second
|
||||
pingPeriod = 55 * time.Second
|
||||
pingPeriod = 25 * time.Second
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
ID string
|
||||
Conn *websocket.Conn
|
||||
Send chan []byte
|
||||
SubscribedPath string
|
||||
done chan struct{}
|
||||
mu *CustomRwMutex
|
||||
}
|
||||
|
||||
func NewClient(conn *websocket.Conn, subscribedPath string) *Client {
|
||||
return &Client{
|
||||
ID: uuid.NewString(),
|
||||
Conn: conn,
|
||||
Send: make(chan []byte, 64),
|
||||
Send: make(chan []byte, 1),
|
||||
SubscribedPath: subscribedPath,
|
||||
done: make(chan struct{}),
|
||||
mu: NewCustomRwMutex(),
|
||||
done: make(chan struct{}, 1),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,17 +38,14 @@ type Hub struct {
|
||||
Broadcast chan []byte
|
||||
Register chan *Client
|
||||
Unregister chan *Client
|
||||
writeMu *CustomRwMutex
|
||||
readMu *CustomRwMutex
|
||||
}
|
||||
|
||||
func NewHub() *Hub {
|
||||
return &Hub{
|
||||
Broadcast: make(chan []byte),
|
||||
Register: make(chan *Client),
|
||||
Unregister: make(chan *Client),
|
||||
Broadcast: make(chan []byte, 1),
|
||||
Register: make(chan *Client, 1),
|
||||
Unregister: make(chan *Client, 1),
|
||||
Clients: make(map[*Client]bool),
|
||||
writeMu: NewCustomRwMutex(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,18 +57,21 @@ func (h *Hub) Run() {
|
||||
h.Clients[client] = true
|
||||
log.Println("Client registered")
|
||||
case c := <-h.Unregister:
|
||||
if _, ok := h.Clients[c]; ok {
|
||||
if v, ok := h.Clients[c]; ok {
|
||||
fmt.Println(v, c)
|
||||
delete(h.Clients, c)
|
||||
close(c.Send)
|
||||
}
|
||||
log.Println("Client Unregistered")
|
||||
case message := <-h.Broadcast:
|
||||
for client := range h.Clients {
|
||||
select {
|
||||
case client.Send <- message:
|
||||
default:
|
||||
close(client.Send)
|
||||
delete(h.Clients, client)
|
||||
}
|
||||
client.Send <- message
|
||||
// select {
|
||||
// case client.Send <- message:
|
||||
// default:
|
||||
// close(client.Send)
|
||||
// delete(h.Clients, client)
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,15 +92,18 @@ func WritePump(c *Client, h *Hub) {
|
||||
c.Conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
if !ok {
|
||||
c.Conn.WriteMessage(websocket.CloseMessage, []byte{})
|
||||
fmt.Println(ok)
|
||||
return
|
||||
}
|
||||
|
||||
if err := c.Conn.WriteMessage(websocket.TextMessage, message); err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
case <-pingTicker.C:
|
||||
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 {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -112,7 +116,7 @@ func ReadPump(c *Client, h *Hub) {
|
||||
c.Conn.Close()
|
||||
}()
|
||||
|
||||
c.Conn.SetReadLimit(512)
|
||||
c.Conn.SetReadLimit(1024)
|
||||
c.Conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
c.Conn.SetPongHandler(func(string) error {
|
||||
c.Conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
@@ -129,7 +133,7 @@ func ReadPump(c *Client, h *Hub) {
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
// import (
|
||||
// "context"
|
||||
// "fmt"
|
||||
// "time"
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
// "git.neurocipta.com/rogerferdinan/safe-web-socket/internal"
|
||||
// "github.com/gorilla/websocket"
|
||||
// )
|
||||
custom_rwmutex "git.neurocipta.com/rogerferdinan/custom-rwmutex"
|
||||
safemap "git.neurocipta.com/rogerferdinan/safe-map"
|
||||
"git.neurocipta.com/rogerferdinan/safe-web-socket/internal"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// const (
|
||||
// pingPeriod = 30 * time.Second
|
||||
// )
|
||||
const (
|
||||
pingPeriod = 10 * time.Second
|
||||
readDeadline = 30 * time.Second
|
||||
)
|
||||
|
||||
// type SafeWebsocketClientBuilder struct {
|
||||
// baseHost *string `nil_checker:"required"`
|
||||
// basePort *uint16 `nil_checker:"required"`
|
||||
// }
|
||||
type MessageType uint
|
||||
|
||||
// func NewSafeWebsocketClientBuilder() *SafeWebsocketClientBuilder {
|
||||
// return &SafeWebsocketClientBuilder{}
|
||||
// }
|
||||
const (
|
||||
MessageTypeText MessageType = websocket.TextMessage
|
||||
MessageTypePing MessageType = websocket.PingMessage
|
||||
MessageTypePong MessageType = websocket.PongMessage
|
||||
MessageTypeClose MessageType = websocket.CloseMessage
|
||||
)
|
||||
|
||||
// func (b *SafeWebsocketClientBuilder) BaseHost(host string) *SafeWebsocketClientBuilder {
|
||||
// b.baseHost = &host
|
||||
// return b
|
||||
// }
|
||||
type Message struct {
|
||||
MessageType MessageType
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// func (b *SafeWebsocketClientBuilder) BasePort(port uint16) *SafeWebsocketClientBuilder {
|
||||
// b.basePort = &port
|
||||
// return b
|
||||
// }
|
||||
type SafeWebsocketClientBuilder struct {
|
||||
baseHost *string `nil_checker:"required"`
|
||||
basePort *uint16 `nil_checker:"required"`
|
||||
headers *map[string]string
|
||||
path *string
|
||||
rawQuery *string
|
||||
isDrop *bool
|
||||
useTLS *bool
|
||||
channelSize *int64
|
||||
writeChannelSize *int64
|
||||
}
|
||||
|
||||
// func (b *SafeWebsocketClientBuilder) Build() (*SafeWebsocketClient, error) {
|
||||
// if err := internal.NilChecker(b); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
func NewSafeWebsocketClientBuilder() *SafeWebsocketClientBuilder {
|
||||
return &SafeWebsocketClientBuilder{}
|
||||
}
|
||||
|
||||
// ctx, cancel := context.WithCancel(context.Background())
|
||||
func (b *SafeWebsocketClientBuilder) BaseHost(host string) *SafeWebsocketClientBuilder {
|
||||
b.baseHost = &host
|
||||
return b
|
||||
}
|
||||
|
||||
// wsClient := SafeWebsocketClient{
|
||||
// baseHost: b.baseHost,
|
||||
// basePort: b.basePort,
|
||||
// ctx: ctx,
|
||||
// cancel: cancel,
|
||||
// reconnectCh: make(chan struct{}, 1),
|
||||
// isConnected: false,
|
||||
// }
|
||||
func (b *SafeWebsocketClientBuilder) BasePort(port uint16) *SafeWebsocketClientBuilder {
|
||||
b.basePort = &port
|
||||
return b
|
||||
}
|
||||
|
||||
// if err := wsClient.connect(); err != nil {
|
||||
// cancel()
|
||||
// return nil, fmt.Errorf("failed to establish initial connection: %v", err)
|
||||
// }
|
||||
func (b *SafeWebsocketClientBuilder) Headers(headers map[string]string) *SafeWebsocketClientBuilder {
|
||||
b.headers = &headers
|
||||
return b
|
||||
}
|
||||
|
||||
// wsClient.startPingTicker()
|
||||
// wsClient.startReceiveHandler()
|
||||
func (b *SafeWebsocketClientBuilder) UseTLS(useTLS bool) *SafeWebsocketClientBuilder {
|
||||
b.useTLS = &useTLS
|
||||
return b
|
||||
}
|
||||
|
||||
// return &wsClient, nil
|
||||
// }
|
||||
func (b *SafeWebsocketClientBuilder) Path(path string) *SafeWebsocketClientBuilder {
|
||||
b.path = &path
|
||||
return b
|
||||
}
|
||||
|
||||
// type SafeWebsocketClient struct {
|
||||
// baseHost *string
|
||||
// basePort *uint16
|
||||
// mu *internal.CustomRwMutex
|
||||
// ctx context.Context
|
||||
// cancel context.CancelFunc
|
||||
// reconnectCh chan struct{}
|
||||
// isConnected bool
|
||||
// }
|
||||
func (b *SafeWebsocketClientBuilder) RawQuery(rawQuery string) *SafeWebsocketClientBuilder {
|
||||
b.rawQuery = &rawQuery
|
||||
return b
|
||||
}
|
||||
|
||||
// func (wsClient *SafeWebsocketClient) connect() error {
|
||||
// url := fmt.Sprintf("%s:%d", *wsClient.baseHost, *wsClient.basePort)
|
||||
// conn, _, err := websocket.DefaultDialer.Dial(url, nil)
|
||||
// if err != nil {
|
||||
// return fmt.Errorf("failed to connect to %s: %w", *wsClient.baseHost, err)
|
||||
// }
|
||||
func (b *SafeWebsocketClientBuilder) IsDrop(isDrop bool) *SafeWebsocketClientBuilder {
|
||||
b.isDrop = &isDrop
|
||||
return b
|
||||
}
|
||||
|
||||
// conn.SetPingHandler(func(pingData string) error {
|
||||
// conn.WriteMessage(websocket.PongMessage, []byte(pingData))
|
||||
// })
|
||||
// }
|
||||
func (b *SafeWebsocketClientBuilder) ChannelSize(channelSize int64) *SafeWebsocketClientBuilder {
|
||||
b.channelSize = &channelSize
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *SafeWebsocketClientBuilder) WriteChannelSize(writeChannelSize int64) *SafeWebsocketClientBuilder {
|
||||
b.writeChannelSize = &writeChannelSize
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketClient, error) {
|
||||
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
|
||||
}
|
||||
|
||||
if b.writeChannelSize == nil {
|
||||
writeChannelSize := int64(1)
|
||||
b.writeChannelSize = &writeChannelSize
|
||||
}
|
||||
|
||||
wsClient := SafeWebsocketClient{
|
||||
baseHost: *b.baseHost,
|
||||
basePort: *b.basePort,
|
||||
headers: b.headers,
|
||||
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, *b.writeChannelSize),
|
||||
}
|
||||
|
||||
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
|
||||
headers *map[string]string
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
header := make(http.Header)
|
||||
|
||||
if wsClient.headers != nil {
|
||||
for k, v := range *wsClient.headers {
|
||||
header.Set(k, v)
|
||||
}
|
||||
}
|
||||
|
||||
conn, _, err := websocket.DefaultDialer.Dial(newURL.String(), header)
|
||||
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
|
||||
|
||||
conn.SetPingHandler(func(pingData string) error {
|
||||
if err := conn.SetReadDeadline(time.Now().Add(readDeadline)); err != nil {
|
||||
log.Printf("error on read deadline: %v\n", err)
|
||||
return err
|
||||
}
|
||||
|
||||
wsClient.writeChan <- Message{
|
||||
MessageType: MessageTypePong,
|
||||
Data: []byte(pingData),
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
conn.SetPongHandler(func(pingData string) error {
|
||||
if err := conn.SetReadDeadline(time.Now().Add(readDeadline)); err != nil {
|
||||
log.Printf("error on read deadline: %v\n", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
go wsClient.writePump()
|
||||
go wsClient.readPump()
|
||||
|
||||
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)
|
||||
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
|
||||
})
|
||||
|
||||
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:
|
||||
if wsClient.isDrop {
|
||||
log.Println("Data channel full, dropping message")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (wsClient *SafeWebsocketClient) startPingTicker(ctx context.Context) {
|
||||
ticker := time.NewTicker(pingPeriod)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Println("ping ticker canceled by context")
|
||||
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
|
||||
|
||||
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) CloseDataChannel() {
|
||||
close(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
|
||||
}
|
||||
|
||||
@@ -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(10 * 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(10 * 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()
|
||||
}
|
||||
60
v1/examples/client/main.go
Normal file
60
v1/examples/client/main.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"net/http"
|
||||
_ "net/http/pprof"
|
||||
|
||||
"git.neurocipta.com/rogerferdinan/safe-web-socket/v1/client"
|
||||
)
|
||||
|
||||
func main() {
|
||||
go func() {
|
||||
log.Println("Starting pprof server on :6060")
|
||||
log.Println(http.ListenAndServe(":6060", nil))
|
||||
}()
|
||||
|
||||
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).
|
||||
Headers(map[string]string{
|
||||
"X-MBX-APIKEY": "abcd",
|
||||
}).Path("/ws/test/data_1").
|
||||
UseTLS(false).
|
||||
ChannelSize(1).
|
||||
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))
|
||||
}
|
||||
}
|
||||
28
v1/examples/gobwas-server/main.go
Normal file
28
v1/examples/gobwas-server/main.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func setMaxRLimit() {
|
||||
var rLimit syscall.Rlimit
|
||||
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
rLimit.Cur = rLimit.Max
|
||||
if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
setMaxRLimit()
|
||||
// pooler, err := netpool.New()
|
||||
|
||||
// http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
// if _, _, _, err := ws.UpgradeHTTP(r, w); err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
// })
|
||||
// epoller, err := MkEp
|
||||
}
|
||||
53
v1/examples/server/main.go
Normal file
53
v1/examples/server/main.go
Normal file
@@ -0,0 +1,53 @@
|
||||
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).
|
||||
ApiKey("abcd").
|
||||
HandleFuncWebsocket("/ws/test/", "data_1", func(c chan []byte) {
|
||||
ticker := time.NewTicker(100 * 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(100 * 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()
|
||||
}
|
||||
@@ -5,22 +5,32 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"git.neurocipta.com/rogerferdinan/safe-web-socket/internal"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
func setMaxRLimit() {
|
||||
var rLimit syscall.Rlimit
|
||||
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
rLimit.Cur = rLimit.Max
|
||||
if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
type SafeWebsocketServerBuilder struct {
|
||||
baseHost *string `nil_checker:"required"`
|
||||
basePort *uint16 `nil_checker:"required"`
|
||||
apiKey *string `nil_checker:"required"`
|
||||
upgrader *websocket.Upgrader `nil_checker:"required"`
|
||||
mux *http.ServeMux `nil_checker:"required"`
|
||||
}
|
||||
|
||||
func NewSafeWebsocketServerBuilder() *SafeWebsocketServerBuilder {
|
||||
h := internal.NewHub()
|
||||
h.Run()
|
||||
|
||||
return &SafeWebsocketServerBuilder{
|
||||
upgrader: &websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
@@ -43,16 +53,17 @@ func (b *SafeWebsocketServerBuilder) BasePort(basePort uint16) *SafeWebsocketSer
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *SafeWebsocketServerBuilder) HandleFunc(
|
||||
pattern string, fn func(http.ResponseWriter, *http.Request),
|
||||
) *SafeWebsocketServerBuilder {
|
||||
func (b *SafeWebsocketServerBuilder) ApiKey(apiKey string) *SafeWebsocketServerBuilder {
|
||||
b.apiKey = &apiKey
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *SafeWebsocketServerBuilder) HandleFunc(pattern string, fn func(http.ResponseWriter, *http.Request)) *SafeWebsocketServerBuilder {
|
||||
b.mux.HandleFunc(pattern, fn)
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *SafeWebsocketServerBuilder) HandleFuncWebsocket(
|
||||
pattern string, subscribedPath string, writeFunc func(chan []byte),
|
||||
) *SafeWebsocketServerBuilder {
|
||||
func (b *SafeWebsocketServerBuilder) HandleFuncWebsocket(pattern string, subscribedPath string, writeFunc func(chan []byte)) *SafeWebsocketServerBuilder {
|
||||
h := internal.NewHub()
|
||||
h.Run()
|
||||
|
||||
@@ -82,22 +93,37 @@ func (b *SafeWebsocketServerBuilder) Build() (*SafeWebsocketServer, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
setMaxRLimit()
|
||||
safeServer := SafeWebsocketServer{
|
||||
url: fmt.Sprintf("%s:%d", *b.baseHost, *b.basePort),
|
||||
mux: b.mux,
|
||||
mux: b.mux,
|
||||
url: fmt.Sprintf("%s:%d", *b.baseHost, *b.basePort),
|
||||
apiKey: *b.apiKey,
|
||||
}
|
||||
return &safeServer, nil
|
||||
}
|
||||
|
||||
type SafeWebsocketServer struct {
|
||||
hub *internal.Hub
|
||||
mux *http.ServeMux
|
||||
url string
|
||||
mux *http.ServeMux
|
||||
url string
|
||||
apiKey string
|
||||
}
|
||||
|
||||
func (s *SafeWebsocketServer) AuthMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-MBX-APIKEY") != s.apiKey {
|
||||
internal.ErrorResponse(w, internal.NewStatusMessage().
|
||||
StatusCode(http.StatusForbidden).
|
||||
Message("X-MBX-APIKEY is missing").
|
||||
Build())
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *SafeWebsocketServer) ListenAndServe() error {
|
||||
log.Printf("HTTP serve on %s\n", s.url)
|
||||
if err := http.ListenAndServe(s.url, s.mux); err != nil {
|
||||
if err := http.ListenAndServe(s.url, s.AuthMiddleware(s.mux)); err != nil {
|
||||
return fmt.Errorf("failed to serve websocket: %w", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
Reference in New Issue
Block a user