-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathconnection.go
59 lines (48 loc) · 1.33 KB
/
connection.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
package nostr
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net/http"
"time"
ws "github.com/coder/websocket"
)
type Connection struct {
conn *ws.Conn
}
func NewConnection(ctx context.Context, url string, requestHeader http.Header, tlsConfig *tls.Config) (*Connection, error) {
c, _, err := ws.Dial(ctx, url, getConnectionOptions(requestHeader, tlsConfig))
if err != nil {
return nil, err
}
c.SetReadLimit(262144) // this should be enough for contact lists of over 2000 people
return &Connection{
conn: c,
}, nil
}
func (c *Connection) WriteMessage(ctx context.Context, data []byte) error {
if err := c.conn.Write(ctx, ws.MessageText, data); err != nil {
return fmt.Errorf("failed to write message: %w", err)
}
return nil
}
func (c *Connection) ReadMessage(ctx context.Context, buf io.Writer) error {
_, reader, err := c.conn.Reader(ctx)
if err != nil {
return fmt.Errorf("failed to get reader: %w", err)
}
if _, err := io.Copy(buf, reader); err != nil {
return fmt.Errorf("failed to read message: %w", err)
}
return nil
}
func (c *Connection) Close() error {
return c.conn.Close(ws.StatusNormalClosure, "")
}
func (c *Connection) Ping(ctx context.Context) error {
ctx, cancel := context.WithTimeoutCause(ctx, time.Millisecond*800, errors.New("ping took too long"))
defer cancel()
return c.conn.Ping(ctx)
}