-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage.go
More file actions
83 lines (71 loc) · 1.75 KB
/
Copy pathmessage.go
File metadata and controls
83 lines (71 loc) · 1.75 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
72
73
74
75
76
77
78
79
80
81
82
83
package wshub
import (
"encoding/json/v2"
"time"
)
// Message represents a WebSocket message.
type Message struct {
// Type is the message type (text, binary, etc.).
Type MessageType
// Data is the raw message data.
Data []byte
// ClientID is the ID of the client that sent the message.
ClientID string
// Time is when the message was received.
Time time.Time
}
// Text returns the message data as a string.
func (m *Message) Text() string {
return string(m.Data)
}
// JSON unmarshals the message data into the provided value.
func (m *Message) JSON(v any) error {
return json.Unmarshal(m.Data, v)
}
// NewMessage creates a new text message.
func NewMessage(data []byte) *Message {
return &Message{
Type: TextMessage,
Data: data,
Time: time.Now(),
}
}
// NewTextMessage creates a new text message from a string.
func NewTextMessage(text string) *Message {
return &Message{
Type: TextMessage,
Data: []byte(text),
Time: time.Now(),
}
}
// NewBinaryMessage creates a new binary message.
func NewBinaryMessage(data []byte) *Message {
return &Message{
Type: BinaryMessage,
Data: data,
Time: time.Now(),
}
}
// NewJSONMessage creates a new JSON message.
func NewJSONMessage(v any) (*Message, error) {
data, err := json.Marshal(v)
if err != nil {
return nil, err
}
return &Message{
Type: TextMessage,
Data: data,
Time: time.Now(),
}, nil
}
// NewRawJSONMessage creates a text message from pre-encoded JSON data.
// The caller is responsible for ensuring data is valid JSON.
// This avoids the marshaling cost of NewJSONMessage when the JSON
// is already available (e.g., cached or encoded once for fan-out).
func NewRawJSONMessage(data []byte) *Message {
return &Message{
Type: TextMessage,
Data: data,
Time: time.Now(),
}
}