-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent.go
69 lines (61 loc) · 1.61 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
package main
import (
"encoding/json"
"fmt"
"time"
)
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"`
}
type EventHandler func(event Event, c *Client) error
const (
EventSendMessage = "send_message"
EventNewMessage = "new_message"
EventChangeRoom = "change_room"
)
type SendMessageEvent struct {
Message string `json:"message"`
From string `json:"from"`
}
type NewMessageEvent struct {
SendMessageEvent
Sent time.Time `json:"sent"`
}
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)
}
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)
}
var outgoingEvent Event
outgoingEvent.Payload = data
outgoingEvent.Type = EventNewMessage
for client := range c.manager.clients {
if client.chatroom == c.chatroom {
client.egress <- outgoingEvent
}
}
return nil
}
type ChangeRoomEvent struct {
Name string `json:"name"`
}
func ChatRoomHandler(event Event, c *Client) error {
var changeRoomEvent ChangeRoomEvent
if err := json.Unmarshal(event.Payload, &changeRoomEvent); err != nil {
return fmt.Errorf("bad payload in request: %v", err)
}
c.chatroom = changeRoomEvent.Name
return nil
}