/
websocket.go
109 lines (93 loc) · 2.11 KB
/
websocket.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package websocket
import (
"fmt"
"net/http"
"time"
"github.com/itering/substrate-api-rpc/pkg/recws"
)
var (
wsEndPoint = ""
maxCap = 25
)
type WsConn interface {
Dial(urlStr string, reqHeader http.Header)
IsConnected() bool
Close()
WriteMessage(messageType int, data []byte) error
ReadMessage() (messageType int, message []byte, err error)
WriteJSON(v interface{}) error
ReadJSON(v interface{}) error
MarkUnusable()
CloseAndReconnect()
}
func Init(options ...Option) (*PoolConn, error) {
var err error
if wsPool == nil {
factory := func() (*recws.RecConn, error) {
SubscribeConn := &recws.RecConn{
KeepAliveTimeout: 10 * time.Second,
WriteTimeout: time.Second * 30,
ReadTimeout: time.Second * 30,
NonVerbose: true,
HandshakeTimeout: time.Second * 5}
for _, o := range options {
o.Apply(SubscribeConn)
}
SubscribeConn.Dial(wsEndPoint, nil)
return SubscribeConn, err
}
if wsPool, err = NewChannelPool(1, maxCap, factory); err != nil {
fmt.Println("NewChannelPool", err)
}
}
if err != nil {
return nil, err
}
conn, err := wsPool.Get()
return conn, err
}
func SetEndpoint(endpoint string) {
wsEndPoint = endpoint
}
// SetChannelPoolMaxCap set connection pool max cap
func SetChannelPoolMaxCap(max int) {
maxCap = max
}
func Close() {
if wsPool != nil {
wsPool.Close()
wsPool = nil
}
}
type Option interface {
Apply(*recws.RecConn)
}
type OptionFunc func(*recws.RecConn)
func (f OptionFunc) Apply(conn *recws.RecConn) {
f(conn)
}
func WithHandshakeTimeout(t time.Duration) Option {
return OptionFunc(func(m *recws.RecConn) {
m.HandshakeTimeout = t
})
}
func WithWriteTimeoutTimeout(t time.Duration) Option {
return OptionFunc(func(m *recws.RecConn) {
m.WriteTimeout = t
})
}
func WithReadTimeoutTimeout(t time.Duration) Option {
return OptionFunc(func(m *recws.RecConn) {
m.ReadTimeout = t
})
}
func WithReadBufferSize(size int) Option {
return OptionFunc(func(m *recws.RecConn) {
m.ReadBufferSize = size
})
}
func WithWriteBufferSize(size int) Option {
return OptionFunc(func(m *recws.RecConn) {
m.WriteBufferSize = size
})
}