Repository navigation
Expand file tree
/
Copy pathsocket_connection.go
More file actions
71 lines (60 loc) · 2.55 KB
/
Copy pathsocket_connection.go
File metadata and controls
71 lines (60 loc) · 2.55 KB
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
package velaros
import (
"context"
"github.com/coder/websocket"
)
// WebSocketConnection is a SocketConnection implementation that wraps
// github.com/coder/websocket.Conn. This is the default connection type used by the
// router when handling HTTP WebSocket upgrades.
type WebSocketConnection struct {
webSocketConnection *websocket.Conn
}
var _ SocketConnection = &WebSocketConnection{}
// NewWebSocketConnection creates a WebSocketConnection from a github.com/coder/websocket.Conn.
// This is used internally by the router. Most applications don't need to call this directly
// unless implementing custom connection handling with Router.HandleConnection.
func NewWebSocketConnection(websocketConnection *websocket.Conn) *WebSocketConnection {
return &WebSocketConnection{
webSocketConnection: websocketConnection,
}
}
// Read reads the next message from the WebSocket connection. Blocks until a message
// arrives or an error occurs. Implements SocketConnection.Read.
func (c *WebSocketConnection) Read(ctx context.Context) (*SocketMessage, error) {
messageType, data, err := c.webSocketConnection.Read(ctx)
if err != nil {
return nil, err
}
return &SocketMessage{
Type: messageType,
RawData: data,
}, nil
}
// Write sends a message to the WebSocket connection. Implements SocketConnection.Write.
func (c *WebSocketConnection) Write(ctx context.Context, msg *SocketMessage) error {
return c.webSocketConnection.Write(ctx, msg.Type, msg.Data)
}
// Close closes the WebSocket connection with the given status code and reason.
// Implements SocketConnection.Close.
func (c *WebSocketConnection) Close(status Status, reason string) error {
return c.webSocketConnection.Close(websocket.StatusCode(status), reason)
}
// Ping sends a WebSocket-protocol PING frame and blocks until the peer's
// PONG arrives or ctx expires. Implements Pinger so the router can run
// application-level liveness checks (see Router.SetPingInterval).
//
// Underlying library auto-filters PING/PONG frames, so callers of Read never
// see them.
func (c *WebSocketConnection) Ping(ctx context.Context) error {
return c.webSocketConnection.Ping(ctx)
}
// Pinger is an optional extension to SocketConnection. Connection
// implementations that can send a ping frame and observe the peer's pong
// should implement it to opt in to Router-driven liveness checks.
//
// The standard WebSocketConnection implements this. Custom SocketConnection
// implementations may omit it (in which case the router skips the ping loop
// for those connections).
type Pinger interface {
Ping(ctx context.Context) error
}