-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathevent.go
99 lines (79 loc) · 2.5 KB
/
event.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
package main
import (
"encoding/json"
"fmt"
"time"
)
// Event is the Messages sent over the websocket
// Used to differ between different actions
type Event struct {
// Type is the message type sent
Type string `json:"type"`
// Payload is the data Based on the Type
Payload json.RawMessage `json:"payload"`
}
// EventHandler is a function signature that is used to affect messages on the socket and triggered
// depending on the type
type EventHandler func(event Event, c *Client) error
const (
// EventSendMessage is the event name for new chat messages sent
EventSendMessage = "send_message"
// EventNewMessage is a response to send_message
EventNewMessage = "new_message"
// EventChangeRoom is event when switching rooms
EventChangeRoom = "change_room"
)
// SendMessageEvent is the payload sent in the
// send_message event
type SendMessageEvent struct {
Message string `json:"message"`
From string `json:"from"`
}
// NewMessageEvent is returned when responding to send_message
type NewMessageEvent struct {
SendMessageEvent
Sent time.Time `json:"sent"`
}
// SendMessageHandler will send out a message to all other participants in the chat
func SendMessageHandler(event Event, c *Client) error {
// Marshal Payload into wanted format
var chatevent SendMessageEvent
if err := json.Unmarshal(event.Payload, &chatevent); err != nil {
return fmt.Errorf("bad payload in request: %v", err)
}
// Prepare an Outgoing Message to others
var broadMessage NewMessageEvent
broadMessage.Sent = time.Now()
broadMessage.Message = chatevent.Message
broadMessage.From = chatevent.From
data, err := json.Marshal(broadMessage)
if err != nil {
return fmt.Errorf("failed to marshal broadcast message: %v", err)
}
// Place payload into an Event
var outgoingEvent Event
outgoingEvent.Payload = data
outgoingEvent.Type = EventNewMessage
// Broadcast to all other Clients
for client := range c.manager.clients {
// Only send to clients inside the same chatroom
if client.chatroom == c.chatroom {
client.egress <- outgoingEvent
}
}
return nil
}
type ChangeRoomEvent struct {
Name string `json:"name"`
}
// ChatRoomHandler will handle switching of chatrooms between clients
func ChatRoomHandler(event Event, c *Client) error {
// Marshal Payload into wanted format
var changeRoomEvent ChangeRoomEvent
if err := json.Unmarshal(event.Payload, &changeRoomEvent); err != nil {
return fmt.Errorf("bad payload in request: %v", err)
}
// Add Client to chat room
c.chatroom = changeRoomEvent.Name
return nil
}