Skip to content

Commit

Permalink
Adds possobility to provide custom ws dialler
Browse files Browse the repository at this point in the history
  • Loading branch information
ksysoev committed Sep 30, 2024
1 parent 7bbcacf commit c794de7
Showing 1 changed file with 36 additions and 5 deletions.
41 changes: 36 additions & 5 deletions backend/ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package backend

import (
"bytes"
"context"
"errors"
"fmt"
"io"
"sync"

Expand All @@ -12,25 +12,37 @@ import (
"golang.org/x/sync/singleflight"
)

type WSBackendOptions func(*WSBackend)

type WSDialler func(ctx context.Context, baseURL string) (*websocket.Conn, error)

type WSBackend struct {

Check failure on line 19 in backend/ws.go

View workflow job for this annotation

GitHub Actions / tests (1.22.x)

fieldalignment: struct with 56 pointer bytes could be 48 (govet)
group *singleflight.Group
connections map[string]*websocket.Conn
lock *sync.RWMutex
factory WSRequestFactory
URL string
dialer WSDialler
}

type WSRequestFactory func(r wasabi.Request) (websocket.MessageType, []byte, error)

// NewWSBackend creates a new instance of WSBackend with the specified URL.
func NewWSBackend(url string, factory WSRequestFactory) *WSBackend {
return &WSBackend{
func NewWSBackend(base_url string, factory WSRequestFactory, opts ...WSBackendOptions) *WSBackend {

Check failure on line 31 in backend/ws.go

View workflow job for this annotation

GitHub Actions / tests (1.22.x)

var-naming: don't use underscores in Go names; func parameter base_url should be baseURL (revive)
b := &WSBackend{
group: &singleflight.Group{},
connections: make(map[string]*websocket.Conn),
lock: &sync.RWMutex{},
factory: factory,
URL: url,
URL: base_url,
dialer: dialler,
}

for _, opt := range opts {
opt(b)
}

return b
}

// Handle handles the incoming request from the WebSocket connection.
Expand Down Expand Up @@ -65,7 +77,6 @@ func (b *WSBackend) getConnection(conn wasabi.Connection) (*websocket.Conn, erro
}

uws, err, _ := b.group.Do(conn.ID(), func() (interface{}, error) {
fmt.Println("Connecting to", b.URL, "for connection", conn.ID())
c, resp, err := websocket.Dial(conn.Context(), b.URL, nil)

if err != nil {
Expand Down Expand Up @@ -149,3 +160,23 @@ func (b *WSBackend) responseHandler(server *websocket.Conn, client wasabi.Connec

err = ctx.Err()
}

func dialler(ctx context.Context, baseURL string) (*websocket.Conn, error) {
c, resp, err := websocket.Dial(ctx, baseURL, nil)

if err != nil {
return nil, err
}

if resp.Body != nil {
defer resp.Body.Close()
}

return c, nil
}

func WithWSDialler(dialer WSDialler) WSBackendOptions {
return func(b *WSBackend) {
b.dialer = dialer
}
}

0 comments on commit c794de7

Please sign in to comment.